微信小程序-自定义组件

2018-07-08  本文已影响80人  Jianshu9527

一、组件

在平常的页面开发中,一般都会遇到很多相同的功能展示区(头部和底部以及侧边栏等),如果每个页面都是独立开发,那么对于代码的维护以及迭代往往会增加工作量,所以把某一些部分做成公共的一些东西,那么在需要的地方之间引入哪将大大提高工作效率,其实在HTML中,一个标签就类似于一个封装好的组件,在合适的地方引入需要的标签即可。

二、组件的创建

三、 组件之间的通讯

//component.wxml
<view class='childComponent'>
  <view>{{text}}</view>//text-组件值A
</view>

//component.js
Component({
  /*** 组件的属性列表*/
  properties: {
    text:{        //和组件值A一一对应
      type:String,//当前变量的类型
      value:'' 
    }
  },

  /** * 组件的初始数据*/
  data: {

  },

  /*** 组件的方法列表*/
  methods: {
  }
})

//index.wxml
<component text="{{componentText}}"></component>//text对应组件值A

//index.js
Page({
  data:{
    componentText:'确定'
  }
})
//component.wxml
<view class='childComponent'>
  <view bindtap='componentevent'>{{text}}</view>
</view>

//component.js
Component({
  /*** 组件的属性列表*/
  properties: {
    text:{        //和组件值A一一对应
      type:String,//当前变量的类型
      value:'' 
    }
  },

  /** * 组件的初始数据*/
  data: {
    info:'我是子组件的数据'
  },

  /*** 组件的方法列表*/
  methods: {
    componentevent:function(e){
      this.triggerEvent('childEvent',this.data.info,{bubbles:false})
    }
  }
})

//index.wxml
<component text="{{componentText}}" bind:childEvent="parentEvent"></component

//index.js
Page({
  data:{
    componentText:'确定'
  },
  parentEvent: function (e) {
    console.log(e)
  }
})

四、 组件之前的事件监听
1 子组件事件

//component.wxml
<view bindtap='componentEvent'></view>

2 父组件事件

//component.wxml
  methods: {
    componentevent:function(e){
      //childEvent事件名称
      this.triggerEvent('childEvent',this.data.info,{bubbles:false})
    }
  }

//index.html
<component text="{{componentText}}" bind:childEvent="parentEvent"></component>

//index.js
Page({
  data:{
    componentText:'确定'
  },
  parentEvent: function (e) {
    console.log(e)
  }
})
上一篇 下一篇

猜你喜欢

热点阅读