经测试发现,当provide提供为对象或者是某个方法时,子对象取值才会是响应式的。
父组件代码 parent.vue
<template>
<div>
<Child />
<button
class="btn"
@click="clickTest"
>
点击我
</button>
</div>
</template>
<script>
import Child from './child'
export default {
name: '',
components: { Child },
mixins: [],
props: {},
provide () {
return {
objTest: {
status: this.status
},
stringTest: this.on,
fnTest: this.onFn
}
},
data () {
return {
on: true,
status: {
on: true
}
}
},
computed: {},
watch: {},
created () {
},
mounted () {
},
destroyed () {},
methods: {
clickTest () {
this.status.on = !this.status.on
this.on = !this.on
},
onFn () {
return this.on
}
}
}
</script>
<style lang="less" scoped>
.btn{
background:#FF700A;
color:#fff;
margin-top:10px;
padding:10px;
}
</style>
子组件代码 child.vue
<template>
<div style="background:#fff;">
<h3 class="item">
我是测试inject为对象时:<span>{{ objTest.status.on }}</span>
</h3>
<h3 class="item">
我是测试inject为方法时:{{ fnTest() }}
</h3>
<h3 class="item">
我是测试inject为字符串时:{{ stringTest }}
</h3>
</div>
</template>
<script>
export default {
name: '',
components: {},
mixins: [],
props: {},
inject: ['objTest', 'stringTest', 'fnTest'],
data () {
return {}
},
computed: {},
watch: {},
created () {
},
mounted () {},
destroyed () {},
methods: {}
}
</script>
<style lang="less" scoped>
.item{
font-size:14px;
padding:10px;
}
</style>