以下是组件代码,简单地模拟一个tab控件:
<template>
<scroll-view class="wuc-tab" scroll-with-animation scroll-x :scroll-left="scrollLeft">
<div>
<div
v-for="(item, index) in tabList" :key="index"
class="wuc-tab-item"
:class="index == currentTab ? 'cur' : ''"
@tap="onTabChange(index, $event)"
>
<span>{{item.name}}</span>
</div>
</div>
</scroll-view>
</template>
<script>
export default {
props: {
tabList: {
type: Array,
default: []
},
currentTab: {
type: Number,
default: 0
}
},
data() {
return {
};
},
computed: {
scrollLeft() {
return (this.currentTab - 1) * 60;
}
},
methods: {
onTabChange(index, e) {
if (this.currentTab == index) return false;
this.$emit('update:currentTab', index);
this.$emit('change', index);
}
}
};
</script>
<style scope>
div,
scroll-view {
box-sizing: border-box;
}
.wuc-tab {
white-space: nowrap;
}
.wuc-tab-item {
display: inline-block;
margin: 5upx 10upx;
padding: 0 10upx;
}
.wuc-tab-item.cur {
border-bottom: 4upx solid;
}
</style>
以下是调用组件的代码:
<template>
<view>
<wuc-tab
:tabList="candidateTypes"
:currentTab="currentTab"
@change="onTabChange"/>
</view>
</template>
<script>
import WucTab from './component/wuc-tab.vue'
export default {
components: {
WucTab
},
data() {
return {
candidateTypes: [
{
id: 0,
name: "全部"
},
{
id: 1,
name: "子分类1"
},
{
id: 2,
name: "子分类2"
}
],
currentTab: 0
}
},
methods: {
onTabChange(index) {
// 测试在wuc-tab组件中执行this.$emit('update:currentTab', index)并未生效,因此必须在此手工更新
this.currentTab = index;
}
}
}
</script>
经过测试,在组件的onTabChange方法中执行 this.$emit('update:currentTab', index); 语句,currentTab属性的值并没有改变;必须在调用者的onTabChange方法中执行 this.currentTab = index; ,该属性的值才改变。这是怎么回事呢?
1 个回复
gweii (作者)
原因找到了,是自己vue没学到家,在以下代码添加.sync修饰符就可以了。
修改前:
修改后: