前置介绍:
provide
/inject
需要一起使用,以允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深,并在起上下游关系成立的时间里始终生效。如果你熟悉 React,这与 React 的上下文特性很相似
父组件中:
<template>
<div id="app">
{{count}}
<child-component @update:xxx="changeCount"></child-component>
</div>
</template>
<script>
export default {
data: {
count: 2000,
text: 'hello world!'
},
provide: function () { // 依赖注入,解决层级较深,使用props比较难过的时候
return {
text: this.text,
getMap: function () {
console.log('我是根组件中的getMap方法', this.text)
// this.text 打印的结果为undefined
}
}
},
}
</script>
后代组件中:
<template>
<div>
<button >{{text}}</button>
<button @click="handleIncrease">+1000</button>
<button @click="handleReduce">-1000</button>
<button @click="getMap">依赖注入</button>
</div>
</template>
<script>
export default {
inject: ['datas','getMap'], // 和provide联用,依赖注入方式,进来可直接使用this调用
data:{
return {
cc:'测试'
}
}
}
</script>