作用:实现祖先与后代组件的通信。一般为祖孙通信,因为子组件可以用props来通信。
语法:父组件中:provide('car', car) 子组件中:let car = inject('car')
- <template>
- <div class="parent">
- <h2>父组件:{{ name }}---{{ price }}h2>
- <Child>Child>
- div>
- template>
-
- <script>
- import { provide, reactive, toRefs } from 'vue';
- import Child from './childView.vue'
-
- export default {
- components: {
- Child
- },
- setup() {
- let car = reactive({
- name: '法拉利',
- price: '20K'
- })
-
- // provide传递数据
- provide('car', car)
-
- return {
- ...toRefs(car)
- }
- }
- }
- script>
-
- <style>
- .parent {
- padding: 10px;
- background-color: skyblue;
- }
- style>
- <template>
- <div class="child">
- <h2>子组件:{{ name }}---{{ price }}h2>
- <Sun>Sun>
- div>
- template>
-
- <script>
- import Sun from './sunView.vue'
- export default {
- components: {
- Sun
- },
- setup() {
- }
- }
- script>
-
- <style>
- .child {
- padding: 10px;
- background-color: skyblue;
- }
- style>
- <template>
- <div class="sun">
- <h2>孙组件:{{ car.name }}---{{ car.price }}h2>
- div>
- template>
-
- <script>
- import { inject } from 'vue';
-
-
- export default {
- setup() {
- // inject 接收数据
- let car = inject('car')
- return {
- car
- }
- }
- }
- script>
-
- <style>
- .sun {
- padding: 10px;
- background-color: pink;
- }
- style>