【问题标题】:How access “provided / injected” values from a mixin in VueJS?如何从 VueJS 中的 mixin 访问“提供/注入”值?
【发布时间】:2017-11-15 16:50:28
【问题描述】:

我正在尝试从 VueJS 中的 mixin 访问 provided / injected 值。我可以从任何组件中看到这些值,但不能从 mixin 中看到。我正在尝试的可能吗?

https://jsfiddle.net/frang/c6c7kqhp/2/1

let myMixin = {
  inject: ['myDependency'],
  created: function() {
    console.log('in mixin', this.myDependency)
  }
}

Vue.component('my-component', {
  inject: ['myDependency'],
  created: function() {
    console.log('in component', this.myDependency)
  }
})

new Vue({
  el: '#example',
  provide() {
    return {
        myDependency: 'here is my value'
    }
  },
  mixins: [myMixin]
})

【问题讨论】:

    标签: dependency-injection vue.js vuejs2 mixins


    【解决方案1】:

    问题是您试图将 myDependency 属性注入到您提供它的同一个 Vue 实例中。

    指定provide 属性的Vue 实例允许其子组件通过inject 访问该值。但是,您不能在同一实例上inject 提供的值。

    您需要在子组件中使用 mixin:

    Vue.component('my-component', {
      mixin: ['myMixin'],
      created: function() {
        console.log('in component', this.myDependency)
      }
    })
    

    Here's a working fiddle.

    【讨论】:

    • 好的,有没有办法让 mixin 全局化?
    • 让 mixin 全球化?你的意思是通过某种方式来指定主 vue 实例中使用的每个组件都使用相同的 mixin?
    • real use case 你的回答提示尝试另一种方式... :+1:
    • 这是因为提供值的 vue 实例无法通过 inject 访问相同的值。只有子组件可以。这不是 mixin 的问题,这就是所提供值的范围是如何工作的。
    • 顺便问一下,对于应用中的引导实例,您有什么不同的方法吗?
    猜你喜欢
    • 2020-05-30
    • 2017-01-18
    • 2019-12-24
    • 2021-03-15
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 2019-07-02
    相关资源
    最近更新 更多