自定义组件我把它分为简单的三个步骤
1.创建组件 --- 2.编写组件 --- 3.调用,使用组件.
-
创建组件:创建一个list(该文件夹就是自定义组件带的)文件夹,里面包含 josn.wxml.wcss.js 四个文件,然后在josn里面添加 "component":true (作用是声明这一组文件为自定义组件)1524638525(1).jpg
-
编写组件代码
在list.wxml
<view class="list-wrap flex flex-align-center flex-pack-justify"> <view class="flex flex-align-center"> <image src="{{url}}" class="list-img"/> <view> < view>{{name}}<view/> < view>{{type}} </view> </view> <view class="center"> <view class="attion" catchtap="_attention" wx:if="{{!isAttention}}" >关注</view> <view class="attion" catchtap="_attention" wx:if="{{isAttention}}" data-isAttention="isAttention" data-index="index">取消关注</view> <view class="number">{{number}}</view> </view> </view>
在list.wxss中都是css样式了,就不贴代码了
在list.js中:
Component({
options: {
multipleSlots: true // 在组件定义时的选项中启用多slot支持
},
properties:{
name:{
type: String, // 类型(必填),目前接受的类型包括:String, Number, Boolean, Object, Array,
null(表示任意类型)
value: ''
},
type:{
type:String,
value: ''
},
number:{
type:String,
value:''
},
url:{
type:String,
value:''
},
idinfo:{
type:String,
value:''
},
isAttention:{
type:Boolean,
value:''
}
},
// 这里是一些组件内部数据
methods:{
_attention:function () {
var myEventDetail = {}; // detail对象,提供给事件监听函数
var myEventOption = {}; // 触发事件的选项
this.triggerEvent('attention', myEventDetail, myEventOption)
}
}
});
第三步, 使用组件
这里我是在 pages/index/index 页面调用 component/list/list自定义组件
首先在index.json中进行引用说明, 这里是设置自定义组件的标签名和引用路径
"usingComponents": {
"list":"/components/list/list"
}
然后在index.wxml调用组件
<list id="list" bind:attention="_attention"
wx:for="{{lists}}" wx:key="id"
name="{{item.name}}"
url="{{item.url}}"
type="{{item.type}}"
number="{{item.number}}"
idinfo="{{item.id}}"
isAttention="{{item.isAttention}}"
data-isAttention="{{item.isAttention}}" data-index="{{index}}"
></list>
在index.js绑定数据,
// 生命周期函数--监听页面初次渲染完成
onReady: function () {
//获得list组件
this.list = this.selectComponent("#list");
},
/*关注和取消关注*/
_attention(event){
let that = this, isAttention = event.currentTarget.dataset.isattention, index = event.currentTarget.dataset.index;
let boo = "lists[" + index + "].isAttention";
if (isAttention) {
that.setData({
[boo]: false
})
} else {
that.setData({
[boo]: true
})
}
},