父子组件之间如何进行通信呢?
- 父组件传递给子组件:通过props属性;
- 子组件传递给父组件:通过$emit触发事件;
1.父组件
<template>
<div>
<hello-world :titles="titles" @titleClick="titleClick"></hello-world>
<div class="contents">{{contents[currentIndex]}}</div>
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld.vue";
export default {
components: {
HelloWorld
},
data() {
return {
titles: ["衣服", "鞋子", "裤子"],
contents: ["衣服页面", "鞋子页面", "裤子页面"],
currentIndex: 0
};
},
methods: {
titleClick(index) {
this.currentIndex = index;
}
}
};
</script>
<style scoped>
.contents {
margin: 50px 20px;
}
</style>
2.子组件
<template>
<div class="tab">
<div
class="item"
v-for="(item,index) in titles"
:key="index"
@click="titleClick(index)"
:class="{active:currentIndex===index}"
>
<span>{{item}}</span>
</div>
</div>
</template>
<script>
export default {
emits: ["titleClick"],
props: {
titles: {
type: Array,
default() {
return [];
}
}
},
data() {
return {
currentIndex: 0
};
},
methods: {
titleClick(index) {
this.currentIndex = index;
this.$emit("titleClick", index);
}
}
};
</script>
<style scoped>
.tab {
display: flex;
margin-top: 50px;
}
.item {
flex: 1;
text-align: center;
font-size: 30px;
}
.active span {
color: red;
border-bottom: 3px solid red;
padding: 5px 10px;
}
</style>
/*coderwhy老师Vue3+TS学习笔记*/