JVM*_*JVM 3 javascript vue.js vuex vuejs2 vuex-modules
是否有在 vuex 模块或普通 js 模块中使用插件的正确/记录方式?我正在使用事件总线来实现它,不确定它是否是正确/最好的方法。请帮忙。
Plugin1.plugin.js:
const Plugin1 = {
install(Vue, options) {
Vue.mixin({
methods: {
plugin1method(key, placeholderValues = []) {
return key;
},
},
});
},
};
export default Plugin1;
Run Code Online (Sandbox Code Playgroud)
在 App.vue 中:
Vue.use(Plugin1, { messages: this.plugin1data });
Run Code Online (Sandbox Code Playgroud)
在商店/plain-js 模块中:
const vue = new Vue();
const plugin1method = vue.plugin1method;
Run Code Online (Sandbox Code Playgroud)
您可以访问您的Vue实例使用this._vm;
和Vue公司的全球使用import Vue from 'vue';
,然后Vue;
我猜你定义了一个实例方法,所以它是前者 ( this._vm.plugin1method()
)
更新
我不能告诉你应该以哪种方式使用它,因为我看不到你的函数是如何在你的插件中定义的。
然而,这里有一个例子应该说明实例和全局之间的区别
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++;
}
}
});
Run Code Online (Sandbox Code Playgroud)
当您提交增量时,即:this.$store.commit('increment')
两种方法都将执行