一、组件
在平常的页面开发中,一般都会遇到很多相同的功能展示区(头部和底部以及侧边栏等),如果每个页面都是独立开发,那么对于代码的维护以及迭代往往会增加工作量,所以把某一些部分做成公共的一些东西,那么在需要的地方之间引入哪将大大提高工作效率,其实在HTML中,一个标签就类似于一个封装好的组件,在合适的地方引入需要的标签即可。
二、组件的创建
-
先创建一个component文件夹用来放自己定义的各个组件
image.png
-
创建自定义组件的相关文件(wxml、wxss、js、json)会自动进行一些默认的配置
image.png
-
在要引入自定义页面中对应的json文件下引入组件,以键值对的方式引入
image.png
-
在要引入的页面中加入自定义标签
image.png
三、 组件之间的通讯
- 父组件给子组件发送数据
//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:'确定'
}
})
-
结果(index.html)
image.png
-
子组件给父组件发送数据
//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)
}
})
-
结果(index.html点击确定之后)
image.png
四、 组件之前的事件监听
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)
}
})
网友评论