【Vue3组件通信方法】-跨级组件通信

时间:2024-11-21 11:37:41

跨级组件通信可以通过provideinject来实现。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>