案例:
实现点击页面的切换:点击“衣服”,则切换到“衣服列表”;点击“鞋子”,则切换到“鞋子列表”;点击“裤子”,则切换到“裤子页面”。
1.创建App.vue(父组件)和TabControl.vue(子组件)
2.App.vue用于展示TabControl和其对应的页面,TabControl发生了点击则切换到对应页面
3.TabControl.vue用于记录TabControl的点击,并向父组件传递参数
//App.vue
<template>
<div class="app">
<!-- tab-control页面 -->
//:titles="['衣服','鞋子','裤子']" :向子组件传值
//@tabItemClick="tabItemClick":通过v-on监听子组件传递的数据
<tab-control :titles="['衣服','鞋子','裤子']" @tabItemClick="tabItemClick"/>
<!-- 展示内容页面 -->
<h1>{{ pageContents[currentIndex] }}</h1>
</div>
</template>
<script>
import TabControl from './TabControl.vue';
export default {
//注册一个局部组件TabControl
components: {
TabControl
},
data() {
return {
pageContents: ["衣服列表", "鞋子列表", "裤子列表"],
currentIndex:0
}
},
methods: {
//子组件传递的自定义事件
tabItemClick(index) {
//将TabControl点击时的index赋值给currentIndex,以便于pageContents[currentIndex]展示页面
this.currentIndex=index
}
}
}
</script>
<style lang="less" scoped>
</style>
//TabControl.vue
<template>
<div class="tab-control">
<template v-for="(item,index) in titles" :key="item">
<div class="tab-control-item"
//class是动态的,当currentIndex===index为true时,active生效
:class="{ active: currentIndex===index }"
//监听itemClick事件
@click="itemClick(index)">
<span>{{ item }}</span>
</div>
</template>
</div>
</template>
<script>
export default {
//接受父组件传递的titles数据:使用了props的对象用法
props: {
titles: {
type: Array,
default:()=>[]
}
},
data() {
return {
currentIndex:0
}
},
methods: {
itemClick(index) {
//点击titles中的item时,以便active生效
//例如点击index=1的item时,currentIndex=1,active生效;
//再点击index=2的item时,currentIndex=1的active失效,currentIndex=2的active生效
this.currentIndex = index
//定义一个自定义事件“tabItemClick”,并向父组件传递参数,以便父组件进行页面的切换
this.$emit("tabItemClick",index)
}
}
}
</script>
<style scoped>
.tab-control{
display: flex;
height: 44px;
line-height: 44px;
text-align: center;
}
.tab-control-item{
flex: 1;
}
.tab-control-item.active {
color: red;
font-weight: 700;
}
.tab-control-item.active span {
border-bottom: 3px solid red;
padding: 8px;
}
</style>