Component构造器
1 .在项目下新建一个components目录用来存放开发中所有自定义组件。 在components目录下新建一个draw文件夹存放自定义组件。 新建Component 会生成4个文件。
在components目录下
.json 文件
.wxml文件
.js
初始化数据
.wxss 一个意思
2 导入自定义组件
在需要的页面中 在.json 文件中导入
在 .wxml 中使用
事件:
在自定义组件中定义点击的方法
自定义组件中
.wxml
在 .js
在 页面中
.wxml
.js
传值
页面传值到组件
组件: . js
页面 : . js
附上代码
自定义组件:
. wxml
<view class='item' catchtap='click'>
<text>{{itemName.id}}:{{itemName.name}}</text>
</view>
. js
Component({
/**
* 组件的属性列表
*/
properties: {
itemName: {
type: Object,
value:""
}
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
show(e){
this.setData({
})
console.log("show==>"+e)
},
click() {
//触发成功回调
this.triggerEvent("action");
}
}
})
.json
{
"component": true,
"usingComponents": {
}
}
页面
. wxml
<view wx:for="{{array}}" wx:key="index">
<draw id="draw"
itemName="{{item}}"
bind:action="_confirmEvent"
data-id="{{item.name}}" ></draw>
</view>
. js
data: {
array: [
{ id: 11, name: "zz" },
{ id: 22, name: "xx" },
{ id: 33, name: "cc" },
{ id: 44, name: "vv" },
{ id: 55, name: "bb" },
{ id: 66, name: "nn" }
],
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
this.draw = this.selectComponent("#draw");
},
//确认事件
_confirmEvent(e) {
var id =e.currentTarget.dataset.id;
console.log('id==>' + id);
console.log('你点击了确定');
this.draw.show("传值");
},
. json
{
"usingComponents": {
"draw": "../../components/draw/draw"
}
}
最终效果