一:使用说明:指组件之间的传值,尤其是祖孙之间的组件交互。provide是一级组件传过来的数值,inject是下一级组件获取的值
二:示例
//one.vue
<template>
<two></two>
<div style="background-color: #2C3E50;color: #fff;padding: 20px;margin: 10px;">
<p>一级组件的值:{{variableOne}}</p>
<button @click="variableOne = '1111'">一级按钮</button>
</div>
</template>
<script>
import two from './components/two.vue'
import {
ref,
provide,
defineComponent
} from 'vue'
export default defineComponent({
name: 'lycApp',
components: {
two
},
setup(prop, context) {
const variableOne = ref('0000')
provide('getVariable', variableOne)
return {
variableOne
}
}
// provide(){ //这是传值的另一种写法,效果一样
// return{
// getContext:()=>({
// variable:this.variable
// })
// }
// }
})
</script>
//two.vue
<template>
<three></three>
<div style="background-color: chocolate;color: #fff;padding: 20px;margin: 10px;">二级组件的值:{{variableTwo1}}</div>
</template>
<script>
import three from './three.vue'
import {computed,inject} from 'vue'
export default{
name:'two',
components:{
three
},
// inject:['getContext'],
// computed:{
// sonContext(){
// return this.getContext()
// }
// },
setup(props,context){
const variableTwo = inject('getVariable')
const variableTwo1 = computed(()=>{
return variableTwo.value
})
return{
variableTwo1
}
}
}
</script>
//three
<template>
<div style="background-color: darkcyan;color: #fff;padding: 20px;margin: 10px;">
<div>三级组件的值:{{variableThree1}}</div>
<button @click="changeVariable">三级按钮</button>
</div>
</template>
<script>
import {ref,inject,computed} from 'vue'
export default {
name:'three',
setup(props,context){
const variableThree = inject('getVariable')
const variableThree1 = computed(()=>{
return variableThree.value
})
const changeVariable = ()=>{
variableThree.value = '3333'
}
return{
variableThree1,
changeVariable
}
}
}
</script>
<style>
</style>
//效果图
点击一级按钮按钮,一二三级的值都会变成1111。点击三级按钮,一二三级的值都会变成3333