假设有这样两个组件A和B(注意:A、B各自独立,非父子强关系组件,B可灵活替换成其他组件,通过slot传递),A有一个属性hello,B嵌套在A组件中:
<A hello="world">
<B></B>
</A>
// A.vue
<template>
<div>
A: {{hello}}
<slot></slot>
</div>
</template>
<script>
export default {
props: ['hello']
}
</script>
如何在B组件中获取到hello?
<template>
<div>
B: {{hello}}
</div>
</template>
<script>
export default {
props: ['hello']
}
</script>
A
Provide 一个hello
,所有写在 A 里面的组件实例inject
就可以了(哪个组件需要,哪个inject
一下就成了。