1.组件一般创建在components文件夹内
2.先把标题的数据 写在父组件中 也就是页面中 ,在index.js 里的data里定义
data: {
tabs:[
{
id:0,
value:"综合",
isActve:true
},
{
id:1,
value:"销量",
isActve:false
},
{
id:2,
value:"价格",
isActve:false
},
]
},
在index.json中 引用组件
"usingComponents": {
"Searchinput":"../../components/Searchinput/Searchinput",
"Tabs":"../../components/Tabs/Tabs"
},
在首页index.wxml里引入标签显示组件
tabs="{{tabs}}" 给组件传数据
<Searchinput></Searchinput>
<Tabs tabs="{{tabs}}"></Tabs>
在Tabs.js组件中 接收处理数据
/**
* 存放要接收父元素 传递过来的数据
*/
properties: {
tabs:{
type:Array,//数据类型
value:[] //默认值
}
},
在Tabs.wxml里渲染数据
//<slot>: 占位标签 父级标签会替换这个标签
<view class="tabs">
<view class="tabs_title">
<view
wx:for="{{tabs}}"
wx:key="id"
wx:for-index="index"
bindtap="handleItemTab"
data-index="{{index}}"
class="title_item {{item.isActive?'active':''}}" >
{{item.value}}
</view>
</view>
<view class="tabs_content">
<slot></slot>
</view>
</view>
在Tabs.js里处理数据
methods: {
handleItemTab(e){
// 1. 获取点击的索引
const{index} = e.currentTarget.dataset;
// 2. 触发父组建的事件 自定义
this.triggerEvent("tabsItemChange",{index})
}
}
在父组件里监听自定义事件
<!-- bind加事件名 监听自定义时间 handle+事件名 回调事件-->
<Tabs tabs="{{tabs}}" bindtabsItemChange="handleTabsItemChange">
<block wx:if="{{tabs[0].isActive}}">0</block>
<block wx:elif="{{tabs[1].isActive}}">1</block>
<block wx:else="{{tabs[2].isActive}}">2</block>
</Tabs>
js里做回调处理
handleTabsItemChange(e){
//1 获取被点击的标题索引
const {index} = e.detail;
//2 修改原数组
let {tabs} = this.data;
tabs.forEach((v,i)=>i===index?v.isActive=true:v.isActive=false);
//3 赋值到data中
this.setData({
tabs
})
最后结果