provide与inject (依赖注入)
provide与inject
作用:实现祖孙组件间的通信
实例:
父组件
<script setup name="Parent"> import Child from './components/Child.vue' import {reactive,provide} from 'vue' let cars=reactive({ name:'奔驰', price:'100W' }) provide('cars',cars) </script> <template> <div class="Parent">我是祖组件{{cars.name}}---{{cars.price}} <Child/> </div> </template> <style> .Parent{ background-color: aqua; width: 100%; height: 200px; } </style>
子组件
<script setup name="Child"> import Son from './Son.vue' </script> <template> <div class="Child"> <h3>我是child组件</h3> <Son/> </div> </template> <style> .Child{ background-color: blanchedalmond; width: 100%; height: 100px; } </style>
孙组件
<script setup name="Son"> import {inject} from 'vue' const cars=inject('cars') </script> <template> <div class="Son"> <h3>我是son组件</h3> {{cars.name}} </div> </template> <style> .Son{ background-color: brown; width: 100%; height: 50px; } </style>

浙公网安备 33010602011771号