父组件(ancestors.vue)
<template>
<div style="border: 1px solid black">
<p>this is ancestors</p>
<p>ancestors num: {{num}}</p>
<p>name: {{ obj.name }},age: {{ obj.age }}</p>
<button @click="addNum">add ancestors num</button>
<button @click="changeObj">change obj</button>
<son />
</div>
</template>
<script>
import son from "@/components/provide-inject/son.vue" ;
import {ref,reactive,provide} from 'vue'
export default{
components: {
son
},
setup() {
const num = ref(0) ;
const obj = reactive({
name : 'lcc',
age: 70
}) ;
provide('numRef',num) ;
// provide('objReactive',obj) ;
const addNum = () => {
num.value ++
}
const changeObj = () => {
obj.name = 'lcccc' ;
obj.age = 100 ;
}
return {
num,obj,addNum,changeObj
}
}
}
</script>
<style>
</style>
子组件(son.vue)
<template>
<div style="border: 1px solid pink">
<p>this is son template</p>
<p>son Num: {{ sonNum }}</p>
<p>son name: {{ sonObj.name }},son age: {{ sonObj.age }}</p>
<button @click="addNum">add son num</button>
<grandson/>
</div>
</template>
<script>
import grandson from "@/components/provide-inject/grandson.vue" ;
import {ref,reactive,inject} from 'vue';
export default{
components: {
grandson
},
setup () {
// 当没有provide numRef时 sonNum调用默认值10 并提示:injection "numRef" not found.
const sonNum = inject('numRef',ref(10)) ;
// inject当没有获取到父组件provide提供的值且没有默认值时 报错;
const sonObj = inject('objReactive',reactive({'name':'clc',age:50})) ;
const addNum = () => {
sonNum.value ++
}
return {
sonNum,sonObj,addNum
}
}
}
</script>
<style>
</style>
孙子组件(grandson.vue)
<template>
<div style="border: 1px solid blue">
<p>this is grandson template</p>
<p>grandson Num: {{ grandsonNum }}</p>
<p>grandson name: {{ grandsonObj.name }},grandson age: {{ grandsonObj.age }}</p>
<span ref="grandsonSpan">this is span</span>
</div>
</template>
<script>
import {ref,reactive,inject, onMounted} from 'vue';
export default{
setup () {
const grandsonNum = inject('numRef',ref(2))
const grandsonObj = inject('objReactive',reactive({name:'ccl',age:20})) ;
const grandsonSpan = ref(null) ;
// null
console.log(grandsonSpan.value) ;
onMounted(() => {
//<span>this is span</span>
console.log(grandsonSpan.value)
})
return {
grandsonNum,grandsonObj,
grandsonSpan
}
}
}
</script>
<style>
</style>