-
作用:实现祖与后代组件间通信
-
套路:父组件有一个
provide
选项来提供数据,后代组件有一个inject
选项来开始使用这些数据 -
具体写法:
-
祖组件中:
-
setup(){ ...... let car = reactive({name:'奔驰',price:'40万'}) provide('car',car) ...... }
2.后代组件中:
-
setup(props,context){ ...... const car = inject('car') return {car} ...... }
例子:
App.vue
<template> <div class="container"> <h2>我是App(祖)组件</h2> <Child></Child> </div> </template> <script> import {reactive,provide} from 'vue' import Child from './components/Child'; export default { name: 'App', components:{ Child }, setup() { let car = reactive({name:'奔驰',price:'40w'}) provide('car',car) //给自己的后代组件传递数据 //return {car} } } </script> <style> .container{ background-color: grey; padding: 10px; } </style>Child.vue
<template> <div class="child"> <h2>我是child子组件</h2> 汽车:{{car.name}},价格:{{car.price}} <Sun></Sun> </div> </template> <script> import {inject} from 'vue' import Sun from './Sun' export default { name: 'Child', components:{ Sun }, setup() { let car = inject('car') return{car} } } </script> <style> .child{ background-color: skyblue; padding: 10px; } </style>
Sun.vue
<template> <div class="sun"> <h2>我是孙子组件</h2> 汽车:{{name}},价格:{{price}} </div> </template> <script> import {inject,toRefs} from 'vue' export default { name: 'Child', setup() { let car = inject('car') return{...toRefs(car)} } } </script> <style> .sun{ background-color: orange; padding: 10px; } </style>
标签:vue,name,provide,car,inject,组件 From: https://www.cnblogs.com/ixtao/p/17546044.html