在项目中如果需要将父组件的值传入孙子组件vue提供了一个简便的方法,依赖注入,可以直接将父组件的值传入孙子组件,且数据是响应的,可以修改。
父组件:
<template>
<div>
<h1>依赖注入</h1>
<A /><br />
<hr />
</div>
</template>
<script setup>
import { ref, provide } from 'vue';
import A from './A.vue';
const parentNum = ref(100);
provide('fromParent', parentNum);
</script>
<style></style>
子组件:
<template>
<div>
<h1>A组件 Anum:{{ Anum }}</h1>
<hr />
<B />
</div>
</template>
<script setup>
import { inject } from 'vue';
import B from './B.vue';
const Anum = inject('fromParent');
</script>
<style></style>
孙子组件:
<template>
<div>
<h1>B组件Bnum:{{ Bnum }}</h1>
<button @click="changeParent">修改provide</button>
</div>
</template>
<script setup>
import { inject } from 'vue';
const Bnum = inject('fromParent');
const changeParent = () => {
Bnum.value = 100000;
};
</script>
<style></style>
在孙子组件中修改值,父组件和子组件里的值全部更新