一、创建组件
在存放组件的文件夹新建一个.vue文件
二、使用子组件
<template>
<order-tab
v-model="activeValue"
:tabList="tabList"
@onTabChange='changeTab'>
</order-tab>
</template>
<script>
export default {
data(){
return {
tabList:[
{ label: '首页', value: 1 },
{ label: '列表', value: 2 },
{ label: '我的', value: 3 }
],
activeValue:1,
},
changeTab(data){
}
}
}
</script>
组件内的tab切换根据v-model双向绑定实现。
这边我是把tab列表从父组件传递进去
三、子组件
<template>
<view class="box">
<view class="active">
<view class="activeBox" v-for="(item,index) in tabList" :key="item.value"
:class="{'selectText' : activeValue == index+1}" @click="selectedTab(index)">
<view class="text">
{{item.label}}
</view>
</view>
</view>
</view>
</template>
<script>
export default {
model: {
prop: 'value',
event: 'onTabChange'
},
props: {
value: {
type: [String, Number, Object]
},
tabList: {
type: Array
}
},
data() {
return {
activeValue: this.value
}
},
watch: {
value: {
handler(val) {
deep: true
this.activeValue = val.value
}
}
},
computed: {
currentIndex() {
return this.tabList.findIndex(item => item.value == this.value)
}
},
methods: {
selectedTab(i) {
console.log('子组件单击了');
this.$emit('onTabChange', this.tabList[i])
}
}
}
<style>
.selectText {
color:red
}
</style>