来理一理自定义组件的思路
距离下班还有一小时
╮(╯▽╰)╭
1.组件简单使用
组件
注意:com.json中
{
"component": true, //自定义组件声明
"usingComponents": {} //可选项,用于引入其他组件
}
com.wxml
<view class="container">
<view class='red' bindtap='onRed'></view>
<view class='gray'></view>
</view>
com.wxss
.container{
height: 400rpx;
width: 400rpx;
border: 1rpx solid #000;
color: #fff;
}
.red{
width: 400rpx;
height: 200rpx;
background: red;
}
.gray{
width: 400rpx;
height: 200rpx;
background: gray;
}
组件写好了,接下来引用。
要使用组件的页面
打开要引入组件的页面,test.json
{
"usingComponents": {
"apple":"/pages/com/com"
}
}
test.wxml
<apple></apple>
引入成功。什么?组件写得太简单了,不要在意这种细节。。。
2.给组件绑定事件
com.wxml
<view class='red' bindtap='onRed'></view
com.js
methods: {
onRed() {
console.log('打印啦啦啦,红色');
}
}
当点击红色块时,可以看见控制台打印输出。
3.页面向组件传值
test.wml
<apple now-in="index" bind:getRed="onGet"></apple>
组件com.js
properties: {
nowIn:String
},
com.wxml
<view class="container">
<view class='red'></view>
<view class='gray'></view>
</view>
<view>{{nowIn}} is here</view>
结果
这里我们要注意,在页面定义自定义属性时是 “now-in”,在组件js中接收是 “nowIn”,驼峰的写法。
可以使用this.data,可看见传过来的数据。
4.组件向页面传值
com.js
methods: {
onRed() {
console.log('打印啦啦啦,红色');
this.triggerEvent("getRed", this.data.nowIn);
console.log(this.data);
}
}
test.wxml
<apple now-in="index" bind:getRed="onGet"></apple>
texst.js
onGet(e){
console.log(e);
this.setData({
hhh:e.detail
})
}
在detail中,就可以看见我们想要传的值,nowIn=“index”, 完成传值。
啦啦啦距离下班还有27分钟,嘿嘿嘿~