父子组件之间如何进行通信呢?
父组件传递给子组件:通过props属性;
子组件传递给父组件:通过$emit触发事件;
一、父组件传递给子组件
在开发中很常见的就是父子组件之间通信,比如父组件有一些数据,需要子组件来进行展示:
这个时候我们可以通过props来完成组件之间的通信;
什么是Props呢?
Props是你可以在组件上注册一些自定义的attribute;
父组件给这些attribute赋值,子组件通过attribute的名称获取到对应的值;
Props有两种常见的用法:
方式一:字符串数组,数组中的字符串就是attribute的名称;
方式二:对象类型,对象类型我们可以在指定attribute名称的同时,指定它需要传递的类型、是否是必须的、 默认值等等;
Props的数组用法:
1. 数组用法中我们只能说明传入的attribute的名称,并不能对其进行任何形式的限制,接下来我们来看一下对象的写法是如何让我们的props变得更加完善的。
2. 当使用对象语法的时候,我们可以对传入的内容限制更多:
比如指定传入的attribute的类型;
比如指定传入的attribute是否是必传的;
比如指定没有传入时,attribute的默认值;
String
Number
Boolean
Array
Object
Date
Function
Symbol
Prop 的大小写命名(camelCase vs kebab-case)
HTML 中的 attribute 名是大小写不敏感的,所以浏览器会把所有大写字符解释为小写字符;
这意味着当你使用 DOM 中的模板时,camelCase (驼峰命名法) 的 prop 名需要使用其等价的 kebab-case (短横线分隔命名) 命名;
非Prop的Attribute
什么是非Prop的Attribute呢?
当我们传递给一个组件某个属性,但是该属性并没有定义对应的props或者emits时,就称之为 非Prop的 Attribute;
常见的包括class、style、id属性等;
Attribute继承
当组件有单个根节点时,非Prop的Attribute将自动添加到根节点的Attribute中:
禁用Attribute继承和多根节点
如果我们不希望组件的根元素继承attribute,可以在组件中设置 inheritAttrs: false:
禁用attribute继承的常见情况是需要将attribute应用于根元素之外的其他元素;
我们可以通过 $attrs来访问所有的 非props的attribute;
多个根节点的attribute
多个根节点的attribute如果没有显示的绑定,那么会报警告,我们必须手动的指定要绑定到哪一个属性上:
二、子组件传递给父组件
什么情况下子组件需要传递内容到父组件呢?
当子组件有一些事件发生的时候,比如在组件中发生了点击,父组件需要切换内容;
子组件有一些内容想要传递给父组件的时候;
我们如何完成上面的操作呢?
首先,我们需要在子组件中定义好在某些情况下触发的事件名称;
其次,在父组件中以v-on的方式传入要监听的事件名称,并且绑定到对应的方法中;
最后,在子组件中发生某个事件的时候,根据事件名称触发对应的事件;
我们封装一个CounterOperation.vue的组件:
内部其实是监听两个按钮的点击,点击之后通过 this.$emit的方式发出去事件;
三、组件间通信案例
<template>
<div class="tab-control">
<div
class="tab-control-item"
:class="{active: currentIndex == index}"
v-for="(title, index) in titles"
@click="itemClick(index)">
<span>{{title}}</span>
</div>
</div>
</template>
<script>
export default {
emits: ["titleClick"],
props: {
titles: {
type: Array,
default() {
return []
}
}
},
data() {
return {
currentIndex: 0
}
},
methods: {
itemClick(index) {
this.currentIndex = index;
this.$emit("titleClick", index);
}
}
}
</script>
<style scoped>
.tab-control{
display: flex;
}
.tab-control-item{
flex: 1;
text-align: center;
}
.tab-control-item.active{
color: brown;
}
.tab-control-item.active span {
border-bottom: 3px solid brown;
padding: 5px 10px;
}
</style>
Home.vue页面
<template>
<div>
<!-- 没有定义props时,组件上的属性是定义到非 -->
<tab-control :titles = "titles" @titleClick = "titleClick"></tab-control>
<div class="content">
<h2>{{contents[currentIndex]}}</h2>
</div>
</div>
</template>
<script>
import TabControl from './TabControl.vue';
export default ({
components: {
TabControl
},
data() {
return {
titles: [
"衣服",
"鞋子",
"裤子"
],
contents: ["衣服页面","鞋子页面","裤子页面"],
currentIndex: 0,
}
},
methods: {
titleClick(index) {
this.currentIndex = index;
}
}
})
</script>