将突变添加到 Vuex 商店作为 Vue 插件的一部分 [英] Adding Mutations to Vuex store as part of Vue Plugin

查看:26
本文介绍了将突变添加到 Vuex 商店作为 Vue 插件的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个小型 Vue 插件,它允许用户从任何组件中添加页面通知".我已经成功实现了类似的东西:

I'm creating a small Vue Plugin that allows a user to add a "page notification" from within any component. I've successfully implemented something like:

this.$notifications.add("a message");

它有效!但我必须注册我的插件所需的变更和操作,作为为我的应用程序设置商店其余部分的文件的一部分:

And it works! But I've had to register the mutations and actions required for my plugin to work as part of the file that sets up the rest of the store for my app:

export default new Vuex.Store({...})

有没有办法从我的插件中向我的商店添加动作和变化?目前看起来是这样的:

Is there a way to add actions and mutations to my store from within my plugin? It currently looks like this:

import vuex from './../store';

const MyPlugin = {

  install(Vue, options) {

    // 4. add an instance method
    Vue.prototype.$notifications =
    {
      notificationTypes: {
          0: "warning",
          1: "info"
      },
      add: function (options) {

        let id = "page-notification-" + (vuex.state.pageNotificationsCreated + 1);
        let message = options.message || options || "no message";
        let notificationType = this.notificationTypes[0];

        if(options.notificationType && Number.isInteger(options.notificationType)){
            // Map int to string type
            notificationType = this.notificationTypes[options.notificationType] || notificationType;
        }else{
            // Or use string we were provided ;)
            notificationType = options.notificationType;
        }

        let notification = { id: id, message: message, notificationType: notificationType };
        vuex.dispatch('addNotification', notification);
      }
    }

  }
};

export default MyPlugin;

感谢所有帮助!

推荐答案

将 vuex store 导入你的插件;使其难以重复使用.您应该在插件选项中添加依赖项.

Import vuex store into your plugin; make it hard to reuse. You should put dependences in plugin options.

const MyPlugin = {
     install(vue, { store }){ // now your plugin depend on store
          if (!store) {
               throw new Error("Please provide vuex store.");
          }
          // register your own vuex module 
          store.registerModule({states, mutations, actions });

          // hook vue
     }
}

现在你的插件和 vuex 完全解耦了;易于在其他应用程序中重用.

Now your plugin total decouple with vuex; easy to reuse in other application.

这篇关于将突变添加到 Vuex 商店作为 Vue 插件的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆