小程序事件、组件、生命周期、路由及数据请求

一、事件流

  1. 事件冒泡:从点击的元素开始触发,向上事件传播
阻止事件冒泡:event.stopProPagation()
  1. 事件捕获:多上级元素传递,传递到最具体的元素
btn.addEventListener('click',function() {//回调},true)

二、小程序中事件冒泡和阻止冒泡

bind+事件名="方法名"  向上传递事件,即事件冒泡
catch+事件名="方法名"  阻止事件冒泡

三、小程序生命周期

  1. 整体小程序的生命周期:

    App({
    
      onLaunch() {},   监听小程序初始化,只触发一次
      onShow(){},小程序启动或切换到前台运行
      onHide(),小程序切换到后台运行
      
    })
    
  2. 小程序页面级别的生命周期:

    Page({
      //页面创建完,只触发一次,通常获取后台数据或接收另一个页面的传参时使用
    	onLoad() {},
    	//进入页面就会触发
    	onShow() {},
    	//页面离开时触发
    	onHide() {},
    	//监听页面初次渲染完成
    	onReady() {},
    	//监听页面卸载,类似于vue中destroyed
    	onUnload() {}
    	onReachBottom() {
        console.log('到底页面底部')
      },
      //下拉触发
      onPullDownRefresh() {
        console.log('onPullDownRefresh')
      },
      //点击右上角分享时触发
      onShareAppMessage() {
        
      }
    })
    
  3. 微信小程序的路由管理

两种路由触发模式:

1.标签方式触发
   
  vue:
   <router-link to="">
   
  小程序:<navigator url="要中转的路径?key=value">
  
  接收:通过另一个页面在onload生命周期中接收 
   
2.编程式触发

  vue:
  this.$router.push()
  
  小程序跳转:
  
  wx.navigateTo()  带历史回退
  wx.redirectTo() 不保留历史,跳转到另一个页面,不能返回到上一页面  this.$router.replace()
  wx.switchTab() 只跳转到tabBar页面,不带回退
  wx.reLaunch() 即能跳转到tabBar页面,也能跳转到非tabBar页面,不带历史回退
  
  

4.动态样式

  • 小程序支持的选择器:class选择器,id选择器,标签选择器,群组选择器,伪对象(:before,:after)

  • 可以对class做动态样式处理,例如:

   <button class="{{ index===currentIndex? 'active':'' }}" >
          {{ item.typename }}
    </button>

5.数据请求

JS原生:XMLHttpRequest,fetch
jQuery:$.ajax,$.getJSON,$.post(),$.get()
Vue:axios
React:fetch
微信小程序:wx.request() 与jQuery的$.ajax类似

wx.request({
  url:'', //请求的接口地址
  method:'get|post|put|delete',//请求方式 
  header:{},//设置请求头
  data:{}, //传参
  success() {}, //成功返回
  fail() {},// 失败返回

})

注意:

1.小程序请求的接口必须是https协议
2. 请求接口之前要提前配置接口请求:
  第一种方法:在微信小程序后台配置request合法域名
  第二种方法:在开发者工具--详情--本地配置--勾选‘不校验合法域名’

上拉加载更多
1.onReachBottom() {} 页面自带的生命周期
2.scroll-view  实现局部区域的滚动和加载更多

6.组件

  • 内置组件:微信小程序封装好的组件,直接拿来就能使用
    - swiper:轮播组件,必须要和swiper-item配合使用
例如:

    <swiper 
        class='banner'
        indicator-dots="true"
        indicator-color="#f00"
        indicator-active-color="#ff0"
        circular="true"
      >
      <swiper-item wx:for="{{ banners }}" wx:key="{{ item.id }}">
        <image src="{{ item.imgurl }}"></image>
      </swiper-item>
    </swiper>
    
    参考:https://developers.weixin.qq.com/miniprogram/dev/component/swiper.html
    

  • scroll-view:局部滚动组件,也可以做上拉加载,下拉刷新,例如:
  <scroll-view 
      scroll-y="true" 
      style="height:{{ height }}px;"
      bindscrolltolower="lower" 
  >
   
    <view class="movie-item" wx:for="{{ moveList }}" wx:key="{{ index }}">
        <image src="{{ item.images.small }}"></image>
         <view clas="movie-title">
            {{ item.title }}
         </view>
      
      </view>


  </scroll-view>
  • navigator
  • video或audio
  • 表单相关的组件(即小程序表单标签)
    • button
    • input
    • picker
    • checkbox
    • checkbox-group

2.自定义组件或模板(为了项目方便复用)

  • 自定义模板:

    只复用wxml,css部分,不具有交互功能
    

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-osQoMlGP-1596710472345)(assets/image-20200806102732122.png)]

  • 自定义组件
    • 子组件如何创建
一个完整独立的视图单元(wxml,css,js)

创建和使用组件的步骤:
第一步:创建一个组件:在子组件文件夹上--右建--选择【新建component】选项
第二步:引入组件

    在要引入的父组件中的json文件的usingComponents添加要使用的子组件
  
 例如:
 {
  "usingComponents": {
    "组件名":"要引入的子组件路径",
     "Dialog":"/components/dialog/dialog"
  },
  "navigationBarTitleText": "首页"
}
	
第三步:使用

   在父组件直接使用子组件的标签名:<Dialog />
   

  • 父组件如何获取子组件中的数据或方法

  • 子向父传递事件:

    this.triggerEvent('事件名',选项1,选项2) 类似于vue中的this.$emit('要派发的事件名',要传递数据)
    
  • 微信小程序组件通讯的方式:

    • 父传子
    实现方式类似于vue
    引入子组件
    在子组件上添加自定义属性 例如:title,content
    在子组件上的properties上添加要接收的属性 title,content
    在子组件上通过{{ }}就可以直接使用啦。。。
    
    • 子传父
    实现方式类似于vue
    1.在子组件上触发一个事件 例如:catchtap="confirmmFn"
    2.在对应的confirmFn上添加派发的事件和要向父级传递的数据
     this.triggerEvent('confirm','ok')
     this.triggerEvent('cancel','no')
    3.父组件监听子组件派发过来的事件和要接收的数据
       bind要监听的事件名=“回调方法”
       例如:
       
         <Dialog  
          bindconfirm="confirm"
          bindcancel="cancel"
      />
      
     4.在父组件的js中接收数据
      //监听确定按钮触发的回调
      confirm(e) {
         console.log('监听确定',e.detail)
       },
    
    • 兄弟之间
    A兄弟,B兄弟,C(父组件)三个组件
    
    A-->C--->B
    
    

上代码:

模板文件:
template.wxml文件中能写多个模板,用name区分:

 <template name="demo">
 <view class='tempDemo'>
   <text class='name'>FirstName: {{firstName}}, LastName: {{lastName}}</text>
   <text class='fr' bindtap="clickMe" data-name="{{'Hello! I am '+firstName+' '+LastName+'!'}}"> clcikMe </text>
 </view>
</template>

样式文件:

	<template name="demo">
     <view class='tempDemo'>
       <text class='name'>FirstName: {{firstName}}, LastName: {{lastName}}</text>
       <text class='fr' bindtap="clickMe" data-name="{{'Hello! I am '+firstName+' '+LastName+'!'}}"> clcikMe </text>
     </view>
    </template>

页面引用:
page.wxml

 <!--导入模板-->
 <import src="../../templates/demo/index.wxml" />
 <!--嵌入模板-->
 <view>
   <text>嵌入模板</text>
   <template is="demo" data="{{...staffA}}"></template><!--传入参数,必须是对象-->
   <template is="demo" data="{{...staffB}}"></template><!--传入参数,必须是对象-->
   <template is="demo" data="{{...staffC}}"></template><!--传入参数,必须是对象-->
 </view>

page.wxss

@import "../../templates/demo/index.wxss" /*引入template样式*/

page.js

 Page({
    /**
     * 页面的初始数据
     */
     data: {
       staffA: { firstName: 'Hulk', lastName: 'Hu' },
       staffB: { firstName: 'Shang', lastName: 'You' },
       staffC: { firstName: 'Gideon', lastName: 'Lin' }
     },
    clickMe(e) {
      wx.showToast({ title: e.currentTarget.dataset.name, icon:  "none", duration: 100000 })
    }
 })

Component组件:

组件创建:

新建component目录——创建子目录——新建Component;

组件编写:

新建的component组件也由4个文件构成,与page类似,但是js文件和json文件与页面不同。

js:

      // components/demo/index.js
      Component({
        /**
         * 组件的属性列表
         */
        properties: {
          name: {
            type: String,
            value: ''
         }
       },
     
       /**
        * 组件的初始数据
        */
       data: {
         type: "组件"
       },
     
       /**
        * 组件的方法列表
        */
       methods: {
         click: function () {
           console.log("component!");
         }
       }
     })

json:

     {
      "component": true,
       "usingComponents": {}
     }

组件引用:

页面中引用组件需要在json配置文件中进行配置,代码如下:

      {
       "navigationBarTitleText": "模板demo",
        "usingComponents": {
          "demo": "../../components/demo/index" 
        }
      }

在模板文件中进行使用就行了,name的值为json配置文件中usingComponents的键值:

      <demo name="comp" />
      <!--使用demo组件,并传入值为“comp”的name属性(参数)-->

组件中不会自动引用公共样式,如果需要则需在样式文件中引入:

@import "../../app.wxss";

猜你喜欢

转载自blog.csdn.net/ZiChen_Jiang/article/details/107822909