Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Vue plugin in Store?

Is there a proper / documented way of using a plugin inside vuex module or plain js module? I am using event bus to acheive it, not sure if it is the correct / best way. Please help.

Plugin1.plugin.js:

const Plugin1 = {
  install(Vue, options) {
    Vue.mixin({
      methods: {
        plugin1method(key, placeholderValues = []) {
          return key;
        },
      },
    });
  },
};

export default Plugin1;

In App.vue:

Vue.use(Plugin1, { messages: this.plugin1data });

In store / plain-js module:

const vue = new Vue();
const plugin1method = vue.plugin1method;
like image 235
JVM Avatar asked Mar 05 '23 05:03

JVM


1 Answers

you can access your Vue instance using this._vm;
and the Vue global using import Vue from 'vue'; and then Vue;

I'm guessing you defined an instance method, so it would be the former (this._vm.plugin1method())


update

I can't tell you which way you should use it because it I can't see how your function is defined in your plugin.

However, here is an example that should illustrate the difference between instance and global

const myPlugin = {
  install: function(Vue, options) {
    // 1. add global method or property
    Vue.myGlobalMethod = function() {
      // something logic ...
      console.log("run myGlobalMethod");
    };
    Vue.mixin({
      methods: {
        plugin1method(key, placeholderValues = []) {
          console.log("run mixin method");
          return key;
        }
      }
    });
    // 4. add an instance method
    Vue.prototype.$myMethod = function(methodOptions) {
      console.log("run MyMethod");
      // something logic ...
    };
  }
};

Vue.use(Vuex);
Vue.use(myPlugin);

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      this._vm.$myMethod();
      Vue.myGlobalMethod();
      this._vm.$options.methods.plugin1method();  // <-- plugin mixin custom method
      state.count++;
    }
  }
});

when you commit the increment ie: this.$store.commit('increment') both methods will execute

like image 89
Daniel Avatar answered Mar 16 '23 01:03

Daniel