在小程序自定义组件中,在/components目录下新建自定义组件。
.wxml .wxss 和其他正常页面相同。
自定义组件.js文件如下:
Component({
//父传子:接收父组件传过来的数据
properties: {
data: {
type:Array
}
},
//子组件私有使用的数据
data: {
tabIndex:'0',
},
//子传父:向父组件传递数据
methods: {
Click(e) {
this.setData({
tabIndex:e.currentTarget.dataset.index
})
this.triggerEvent('event',{index:e.currentTarget.dataset.index},{ bubbles: true, composed: true })
}
}
})
注:
properties:组件的对外属性,是属性名到属性设置的映射表。即父传子,对父组件传递的数据进行接收。
父组件使用自定义组件,及向子组件传值:
父组件.json文件:
{
"usingComponents": {
"tab":"../../../../../components/tab/tab-t"
}
}
父组件.wxml文件:
<!--data就是父组件向子组件传递的数据,由子组件properties中对应的字段接收,和data中的数据一样使用-->
<!--3、handleItemChange接收子组件传递过来的数据-->
<tab data="{{tabTitle}}" bindevent="handleItemChange">
<!--如果自定义组件有插槽<slot></slot>,可以在这里放其他结构-->
</tab>
子组件向父组件传值:
子组件.wxml文件:
<view class="tab">
<view wx:for="{{data}}" class="{{tabIndex == index ? 'tab-item active':'tab-item'}}" wx:key="index" data-index="{{index}}" bindtap="Click">
<!--1、定义点击事件click-->
<view>{{item}}</view>
</view>
</view>
<view>
<slot></slot>
</view>
子组件.js文件:
methods: {
Click(e) {
this.setData({
tabIndex:e.currentTarget.dataset.index
})
//2、将要传递给父组件的数据放在一个事件当中
this.triggerEvent('event',{index:e.currentTarget.dataset.index},{ bubbles: true, composed: true })
}
}
父组件.js文件:
//tab栏切换
//4、子组件传递的数据在e中
handleItemChange(e){
console.log(e.detail.index);
},