• Principle: Data injection is implemented by provide and Inject. Provide provides data or methods, and inject data into the current component to obtain the data provided by provide.
  • Disadvantages: Improves coupling between components
  • Solution: If data needs to be modified by injecting components, you are advised to provide methods in Provide to invoke methods to modify data
import { provide, readonly, ref, reactive } from "vue"; export default { name: "App", setup() { let userAge = ref(0); let user = reactive({ name: "sa", age: userAge, }); const changeName = () => { user.name = "zhangsan"; userAge.value = 123; }; provide("user", readonly(user)); // Make the injected data read-only provide("changeName", changeName); // Provide methods to modify the injected data},}Copy the code
<template>
  <div class="hello">
    <el-button  @click="changeData">123</el-button>
  </div>
</template>
import {inject, ref} from 'vue'
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  setup(){
    let count=ref(3)
    // let username=inject('userName','LiSi')
    let user=inject('user')
    let changeName=inject('changeName')
    return {count,user,changeName}
  },
  methods: {
    changeData() {
      console.log(this.changeName);
      this.changeName()
      this.user.namge="qwe"
      this.count++
    }
  },
}
Copy the code

Inject data Modifies the data of Inject by calling the method provided by provide.