跨级组件通信可以通过provide
和inject
来实现。provide
允许父组件提供数据,而inject
允许子孙组件注入这些数据。
// ParentComponent.vue
<template>
<div>
<grandparent-component :message="message" />
</div>
</template>
<script>
import GrandparentComponent from './GrandparentComponent.vue';
export default {
data() {
return {
message: 'Hello from Parent!'
};
},
components: {
GrandparentComponent
}
}
</script>
// GrandparentComponent.vue
<template>
<div>
<parent-component />
</div>
</template>
<script>
import ParentComponent from './ParentComponent.vue';
export default {
provide: {
message: this.message
},
components: {
ParentComponent
}
}
</script>
// ParentComponent.vue
<template>
<div>
<child-component />
</div>
</template>
<script>
import { inject } from 'vue';
export default {
setup() {
const message = inject('message');
return { message };
}
}
</script>