provide和inject用来向后代组件传递数组,也是遵循的是单项数据流 看代码: 在祖先组件中,定义provide数据,如果是响应式的,必须要用ref或者reactive来定义
<template>
App根组件 --- {{money}}
<hr>
<Son />
</template>
<script>
import {provide, ref} from 'vue'
import Son from './son.vue'
export default {
name:'App',
components:{
Son
},
setup() {
let money = ref(100)
function setMoney(value){
money.value -= value
}
provide('money',money)
provide('setMoney',setMoney)
return {
money
}
},
}
</script>
子组件
<template>
son根组件 --- {{money}}
<hr>
<GenderSon />
</template>
<script>
import {inject, ref} from 'vue'
import GenderSon from './genderSon.vue'
export default {
name:'son',
components:{
GenderSon
},
setup() {
let money = inject('money')
return {
money
}
},
}
</script>
孙子组件
<template>
genderSon根组件 --- {{money}}
<button v-on:click="sub">点一次,花10元</button>
</template>
<script>
import {inject, ref} from 'vue'
export default {
name:'genderSon',
setup() {
let money = inject('money')
let fn = inject('setMoney')
function sub(){
fn(10)
}
return {
money,
sub
}
},
}
</script>
|