vue3通过provide和inject实现多层级组件通信

父组件

<template>
  <div>
    <h1>我是父组件 {{num}}</h1>
    <hr>
    <child></child>
  </div>
</template>

<script setup>
import child from './child.vue';
import { ref,provide } from 'vue';
let num = ref(520)
provide('parentNum',num)
</script>

子组件

<template>
  <div>
    <h2>我是子组件</h2>
    <hr>
    <grandchild></grandchild>
  </div>
</template>

<script setup>
import grandchild from './grandchild.vue';
</script>

孙子组件

<template>
  <div>
    <h3>我是孙子组件</h3>
    <p>这是爷爷的值 {{parentNum}}</p>
    <button @click="handler">点击我爷爷的值减100</button>
  </div>
</template>

<script setup>
import { inject } from 'vue';
let parentNum = inject('parentNum')
const handler = () => {
  parentNum.value -= 100
}
</script>

vue3通过provide和inject实现多层级组件通信_第1张图片

你可能感兴趣的:(vue,面试,vue.js,javascript,前端)