十 分分钟学会 vue3, 依赖注入 provide/inject

53 阅读1分钟

1. provide/inject 的作用

可以进行组件深度传参,孙子组件直接获取爷爷组件传递的参数

爷爷组件

<template>
  <div class="about">
    我是爷爷组件: {{ rootData }}
    <!-- 使用自定义组件 绑定class属性-->
    <CustomComponent ></CustomComponent>
  </div>
</template>

<script setup lang="ts">
// 引入自定义组件
import CustomComponent from '@/components/ChildComponent.vue'

import { provide, ref } from "vue";


const rootData = ref('我是爷爷组件的参数')

provide('aaa', rootData)

</script>

父亲组件

<template>
  <div>
    我是子组件
    <!-- 引用子组件 -->
    <DeepChildComponent></DeepChildComponent>
  </div>
</template>

<script setup>
import DeepChildComponent from "@/components/DeepChildComponent.vue";

</script>

<style lang="scss" scoped></style>

孙子组件

<template>
  <div class="bb" c="dd">
      我是孙子组件:
      <div>
        我是爷爷组件传递过来的参数: {{ aaa }}
      </div>
     <button @click="changedata">点击修改爷爷组件的参数</button>
  </div>
</template>

<script setup>
import { inject } from "vue";
const aaa = inject('aaa')

const changedata = () => {
  aaa.value = "修改后的参数"
}
</script>

<style lang="scss" scoped></style>

image.png

2. readonly 防止子组件修改 爷爷组件传递过来的参数

<template>
  <div class="about">
    我是爷爷组件: {{ rootData }}
    <!-- 使用自定义组件 绑定class属性-->
    <CustomComponent ></CustomComponent>
  </div>
</template>

<script setup lang="ts">
// 引入自定义组件
import CustomComponent from '@/components/ChildComponent.vue'

import { provide, ref, readonly } from "vue";


const rootData = ref('我是爷爷组件的参数')

provide('aaa', readonly(rootData))

</script>