1

I'm trying to access provided / injected values from a mixin in VueJS. I can see those values from any component but not from the mixin. Is what I'm attempting possible?

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]
})

1 Answer 1

1

The issue is that you are trying to inject the myDependency property in the same Vue instance that you are providing it.

Vue instances that specify a provide property give their child components access to that value via inject. But, you cannot inject the provided value on the same instance.

You need to use the mixin in a child component:

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

Here's a working fiddle.

Sign up to request clarification or add additional context in comments.

7 Comments

Ok, Is there any way to make the mixin global?
Make the mixin global? Do you mean some way to specify that each component used in the main vue instance uses the same mixin?
The only issue is that the mixin do not have the injected values when created it self, but when the component is created
That's because the vue instance that provides a value cannot access that same value via inject. Only the child components can. That's not a problem with the mixin, that's just how the scope of provided values works.
By the way, do you have any different approach for bootstrap instances in app?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.