Vue 依赖注入

一、功能

通常情况下,父组件向孙组件传递数据,可以采用父子 props 层层传递,也可以使用 event-bus 和 vuex 直接交互。实际上,vue还提供了 provide/inject 选项。
这对选项允许一个祖先组件向其所有子孙后代组件注入一个依赖,不论组件层次有多深,并在起上下游关系成立的时间里始终生效。
也就是说,在父组件只要声明了provide,在其子组件,孙组件,曾孙组件等能形成上下游关系的组件中交互,无论多深都能通过inject来访问provider中的数据。而不是局限于只能从当前父组件的prop属性来获取。注意他只做祖先通后代的单向传递的一个办法。有人这么形容:

provide就相当于加强版父组件prop,可以跨越中间组件,inject就相当于加强版子组件的props

二、用法

父组件代码:

<template>
  <Son />
</template>

<script>
import Son from '@/components/Son'
export default {
    
    
  components: {
    
    
    Son
  },
  data () {
    
    
    return {
    
    
      msg: 'hello world'
    }
  },
  methods: {
    
    
    getMsg () {
    
    
      alert('hello world')
    }
  },
  // 提供变量:
  provide () {
    
    
    return {
    
    
      msg: this.msg,
      getMsg: this.getMsg
    }
  }
}
</script>

子组件代码:

<template>
  <div>
    <p>{
    
    {
    
    msg}}</p>
    <button @click="getMsg">确定</button>
  </div>
</template>

<script>
export default {
    
    
  name: 'Son',
  // 注入变量:
  inject: ['msg', 'getMsg']
}
</script>

猜你喜欢

转载自blog.csdn.net/preoccupied_/article/details/130688818