Vue3 的 provide 和 inject API的使用

2022/8/18 Vue3provideinject

Vue3 的 provide 和 inject API的使用

注意 不要在子组件里修改父组件传来的值 如果要修改请用 emit 传给父组件来修改 这里因为为了方便演示 用了两个组件 如果只是父传子 用 props和emit 这两个API实际是在多个子组件嵌套的时候用的 类似一个树形结构

s

# 父组件

<template>
  <div>
    我是父组件{{ num }}
    <button @click="btn">我是父组件的btn</button>
    <oo></oo>
  </div>
</template>

<script>
import { ref, readonly, provide } from "vue";
import oo from "./oo.vue";
export default {
  components: {
    oo,
  },
  setup(props, { attrs, slots, emit }) {
    let num = ref(0);
    provide("num", readonly(num));
    const btn = () => {
      num.value++;
    };
    return { num, btn };
  },
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# 子组件

<template>
  <div>我是子组件{{ num }}</div>
</template>

<script>
import { inject } from "vue";
export default {
  setup() {
    const num = inject("num");
    return {
      num,
    };
  },
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15