In the process of writing a project, we will use props to pass values between parent and child components, but if the component hierarchy is complex, then dependency injection is needed to solve this problem.
The first step is to introduce provide, inject
import {provide ,inject} from "vue"
1、provide
Provide can provide a value that can be injected by descendant components, and it is a provider that descendant components depend on
// root.vue
import { provide } from "vue";
provide("data", {
name: "cat",
age: 18,
});
2、inject
inject is used to receive the value of the provide statement
// chlid.vue
import { inject } from "vue";
const data = inject("data");
console.log(data);
// { name: "cat", age: 18}
If the parent component does not provide us with a value, we can inject a default value
// chlid.vue
import { inject } from "vue";
const data = inject("data", {
name: "cat",
age: 18,
});
console.log(data);
// log
// { name: "cat", age: 18 }
3. How to ensure that the key provided by provide remains unique? Can't we make sure every developer uses different variable names? We use ES6's unique value of symbol
// root.vue
import { provide } from "vue";
export const dataSymbol=Symbol()
provide(dataSymbol, {
name: "cat",
age: 18,
});
// child.vue
import { inject } from "vue";
const data = inject(dataSymbol, {
name: "cat",
age: 18,
});
4. The data provided can also be responsive
// root.vue
import { provide,ref} from "vue";
const data=ref({
name:cat,
age:18
})
provide(data.value)
5. It is also possible to provide methods
// root.vue
import { ref, provide } from "vue";
const log= () => {
console.log("传递方法");
};
provide(log);
// child.vue
import { inject } from "vue";
import { dataSymbol } from "../injectionSymbols";
const { log } = inject(log);
log()
You can also add a readonly attribute to the passed value, then the passed data cannot be changed