为什么要组件? 将复杂页面拆分为多个组件 ,结构清晰 维护简单,能重复使用
1.定义组件
a.新建目录 components 项目所有的组件都将放在这个目录中
b.在 components 右键新建目录 w-tab-control
c.在 w-tab-control 右键 新建components 会自动生成四个文件(js、json、wxml、wxss)
// 1.w-tab-control.wxml
<view class="titleclass">我是标题</view> //titleclass是使用组件页面传递过来的class
<view class="tab-control">
<block wx:for="{{titles}}" wx:key="{{index}}">
<view class="w-tab-item {{currentIndex == index ? 'active' :'' }}"
bind:tap="tabClick" data-index="{{index}}">
<text >{{item}}</text>
</view>
</block>
</view>
<my-cpn /> //引用的别的组件
// 2.w-tab-control.js
Component({
properties: {
titles:{ //使用组件页面传递过来的数据
type:Array, //表明类型
value:[] //默认值
}
},
externalClasses: ['titleclass'], //接收使用页面传递过来的class
data: {
currentIndex:0
},
methods: {
tabClick:function(e){
var index = e.currentTarget.dataset.index;
this.setData({
currentIndex: index
})
// 将事件传递给使用组件的页面
this.triggerEvent("tabOnClick",
{ index, name: this.properties.titles[index]},
{}
)
},
}
})
// 3.w-tab-control.json
{
"component": true, //当组件用时 不可以删除
"usingComponents": {
"my-cpn":"/components/my-cpn/my-cpn",
} //可以在里面引用别的组件
}
// 4.w-tab-control.wxss
.tab-control{
line-height: 44px;
display: flex;
}
.w-tab-item{
flex: 1;
text-align: center;
}
.active text{
color:red;
border-bottom:3px solid red;
padding:10px 5px;
}
2.引用组件 在/pages/cpn/cpn 中引用组件
// 1. cpn.json
{
"usingComponents": {
"my-cpn":"/components/my-cpn/my-cpn",
"w-tab-control":"/components/w-tab-control/w-tab-control" //引用组件
}
}
// 2.cpn.wxml
//页面使用
// titles 向组件传递数据 在组件js中接收
// bind:tabOnClick="tabclick" 返回的事件
//bind:tabOnClick tabOnClick是返回的名称
// tabclick 当前页面(cpn.js)事件的名称
<w-tab-control
titles="{{['首页','详情','介绍']}}"
titleclass="red"
bind:tabOnClick="tabclick" />
// 3.cpn.js
Page({
tabclick:function(e){ //组件传递过来的事件
console.log(e)
}
})
// 4.cpn.wxss
.red{
color:red
}
注意:组件名称由 (a-z ,- , _ ) 组成 ,不能使用特殊符号 和 大写字母