方案:
- $attrs是用来将数据从爷组件传递给孙组件的。
- $listeners是用来从孙组件中触发爷组件中事件的
具体实现:
- $attrs的使用
- 在爷组件(index.vue)中,类似props传值,将需要传递的值绑定在父组件上。
- 在父组件中,也是类似props传值,但是这里传递的就不是值了,而是$attrs。
- 在孙组件中,接收props,这样就可以在孙组件中使用这个数据了。
(需要注意的是父组件中不需要接收props,只要在孙组件中接收就可以。)
<Father :homeInfo="homeInfo"/>
<Son v-bind="$attrs"/>
<template>
<div class="home">
{{homeInfo.name}}
</div>
</template>
<script>
export default {
name: "Son",
data() {
return {};
},
props: {
homeInfo: {
default: Object,
default: () => {},
},
},
};
</script>
- $listeners的使用
- 在爷组件(index.vue)中,绑定事件。
- 在父组件中,也是类似绑定事件,但是这里绑定的不是具体的事件,而是v-on=“$listeners”。
- 在孙组件中,需要的时候触发($emit)这个事件即可。
<Father :homeInfo="homeInfo" @update="update"/>
<Son v-bind="$attrs" v-on="$listeners"/>
<template>
<div class="home" @click="update">
{{homeInfo.name}}
</div>
</template>
<script>
export default {
name: "Son",
data() {
return {};
},
props: {
homeInfo: {
default: Object,
default: () => {},
},
},
methods: {
update() {
const newHome = {
name: 'new'
}
this.$emit("update", newHome)
}
}
};
</script>