当前位置: 代码迷 >> 综合 >> vue------provide & inject 依赖注入(层级较深时传值)
  详细解决方案

vue------provide & inject 依赖注入(层级较深时传值)

热度:86   发布时间:2024-01-24 05:15:43.0

 前置介绍:

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>

 

  相关解决方案