【问题标题】:How to use Vue plugin in Store?如何在 Store 中使用 Vue 插件?
【发布时间】:2018-10-24 21:15:16
【问题描述】:

是否有在 vuex 模块或纯 js 模块中使用插件的正确/记录方式? 我正在使用事件总线来实现它,不确定它是否是正确/最好的方法。请帮忙。

插件1.plugin.js:

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

export default Plugin1;

在 App.vue 中:

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

在 store/plain-js 模块中:

const vue = new Vue();
const plugin1method = vue.plugin1method;

【问题讨论】:

  • 插件通常在Vue 实例/组件中使用。如果您解释您尝试使用的插件可能会有所帮助,因为一些添加静态方法到 Vue
  • 如果你在谈论 Vuex 插件,请看这里:vuex.vuejs.org/guide/plugins.html。但我猜你正在寻找在 Vuex 中使用 Vue 插件。
  • 是目前在组件中使用的插件。我想在 vuex 中使用相同的插件
  • downvoter,请指出这个问题有什么问题?我正在从事一个复杂的 vue.js 项目,并且拥有足够的知识来提出合法的问题。
  • 我认为@Daniel 在下面的回答中说得最好...... “我无法告诉你应该使用哪种方式,因为我看不到你的功能在您的插件中定义"。请在您的问题中添加更多详细信息

标签: javascript vue.js vuejs2 vuex vuex-modules


【解决方案1】:

您可以使用 this._vm;
访问您的 Vue 实例Vue global 使用 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++;
    }
  }
});

当您提交增量时,即:this.$store.commit('increment') 两种方法都会执行

【讨论】:

  • 其实我的插件是一个全局插件(vuejs.org/v2/guide/plugins.html)。它是使用“Vue.use”加载的。根据这些信息,正确的方法应该是什么?
  • 我已经更新了答案。希望这可以清除它。 codesandbox.io/s/wooz0lm9l8
  • 添加了插件代码以使我的问题更加清晰。一个限制是,我无法更改插件代码。它在那里使用了一个mixin。
  • 在这种情况下,它是一个实例,我已经更新了答案以包含它
  • @Daniel 那么您如何能够在开玩笑的单元测试中访问或阅读this._vm.$myMethod()?看来您“无法读取未定义的属性 $myMethod”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-29
  • 2019-04-23
  • 2023-03-10
  • 2019-09-04
  • 1970-01-01
  • 2017-01-26
  • 2021-09-04
相关资源
最近更新 更多