类似于页面,一个自定义组件由 json wxml wxss js 4个文件组成
首先需要在自定义组件所在的 json 文件中进行自定义组件声明
{
"component": true
}同时,还要在 wxml 文件中编写组件模板,在 wxss 文件中加入组件样式
wxml与xcss和普通页面设置差不多
wxml
<!-- 这是自定义组件的内部WXML结构 -->
<view class="inner">
{{innerText}}
<slot></slot>
</view>xcss
/* 这里的样式只应用于这个自定义组件 */
.inner {
color: red;
}js文件设置有点区别
Component({
properties: {
// 这里定义了innerText属性,属性值可以在组件使用时指定
innerText: {
type: String,
value: 'default value',
}
},
data: {
// 这里是一些组件内部数据
someData: {}
},
methods: {
// 这里是一个自定义方法,方法必须写在methods内
customMethod: function(){}
}
})首先要在页面的 json 文件中进行引用声明。还要提供对应的组件名和组件路径
// 引用声明
"usingComponents": {
// 要使用的组件的名称 // 组件的路径
"component-tag-name": "path/to/the/custom/component"
}
}组件的使用和Vue一样,
在wxml文件中
<component-tag-name></component-tag-name>父组件的wxml页面传输值
<component-tag-name></component-tag-name>子组件的wxml
<view>{{变量名}}</view>让父组件内显示子组件的内容
#在组件中
properties: {
变量名:{
type:String,
value:"变量值"
}
}
//而不是把变量名放在data中父组件页面
页面
<component-tag-name bind:icre="icre"></component-tag-name>父组件的js
页面中js
icre:function(e){
console.log(e)
this.setData({
num:this.data.num+1
})
},子组件页面
<button bindtap='clickpush'>加我</button>子组件的js
clickpush:function(e){
console.log(e)
this.triggerEvent("icre",{"index":13},{})
}