provide 和 inject

provide函数

  • 用于祖先组件传递后代组件数据
  • 接收两个参数:字符串名字,变量

inject函数

  • 用于接收祖先组件传递的数据
  • 接收一个参数: provide 函数的第一个字符串名字
<template>
  <div id="app">
    <h1>我是APP组件 {{name}} --- {{price}}</h1>
    <Child />
  </div>
</template>

<script>
import Child from "./components/Child";
import {reactive, toRefs, provide, } from "vue";
export default {
  name: 'app',
  setup() {
    let car = reactive({
      name: '奔驰',
      price: '100w'
    })
    provide('car', car) // 给后代组合传递数据
    return {
      ...toRefs(car),
    }
  },
  components: {
    Child,
  }
}
</script>

<style>
#app {
  background-color: #42b983;
  height: 300px;
}
</style>
<template>
  <div class="child">
    <div>Child组件</div>
    <Son></Son>
  </div>
</template>

<script>
import Son from './Son'
export default {
  name: "Child",
  components: {
    Son,
  }
}
</script>

<style scoped>
.child {
  background-color: skyblue;
  height: 200px;
}
</style>
<template>
  <div class="son">
    <div>Son组件 {{car.name}} --- {{car.price}}</div>
  </div>
</template>

<script>
import {inject, } from 'vue'
export default {
  name: "Son",
  setup() {
    let car = inject('car')
    return {
      car
    }
  }
}
</script>

<style scoped>
.son {
  background-color: lightpink;
  height: 100px;
}
</style>

 

上一篇:C# 枚举器(enumerator)


下一篇:Essential C++ Chapter 6学习记录(6.1~6.5节的代码)