Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access Vue Instance from mixins?

I would like to implement this kind of logic that assign this.$store.value to local data. This is how I do in pages/index.vue for instance.

method: {
  this.value = this.$store.value
}

I want to write it down into mixins because I actually have another logics around it and I use some pages.

However, I don't know how should I access this(VueInstnce) from mixins?

like image 960
db099u Avatar asked Nov 08 '22 00:11

db099u


1 Answers

It is not supported by Vue because mixin runs first before component's code, then mixin is bound (merged) by Vue to the component instance so it's easy to access mixin from component/instance scope, but not vice versa.

To achieve your need I think the mixin method (like created) should be run (for example) with a given reference to the instance of your component as a parameter, but it's not like that.

However, if you reorganize your code to run what you need from instance.created accessing there methods and data of mixin is possible and passing arguments on your own:

var mixin = {
    data: {mixin: 'mixin'},
    created: function () {
    console.log('mixin hook called')
    },
    methods: { test: function(arg){console.log(arg); } }
};

vm=new Vue({
    data: {component: 'component'},
    mixins: [mixin],
    created: function () {
    console.log('called hook of ' + this.component + ' and accessing ' + this.mixin)
    },
});

vm.test(vm.mixin);
vm.test(vm.component);  // no problem to run mixin's method with component's data
> mixin hook called
> called hook of component and accessing mixin
> mixin
> component
like image 146
Sławomir Lenart Avatar answered Nov 12 '22 13:11

Sławomir Lenart