首页 > 解决方案 > 如何在 vuex 中注册多个插件?

问题描述

我已经在我的项目中使用了vue-persistedstate插件。现在我也需要vuex-pathify插件。

对于持久状态,我准备了一个常量,包括设置:

const persistedStates = [
    createPersistedState({
        key: process.env.PERSISTENT_COOKIE_NAME,
        paths: [
            'auth'
        ],
        storage: {
            getItem: key => JSON.stringify(cookies.get(key)),
            setItem: (key, value) => cookies.set(key, value, { path: '/', expires: '6h', secure: false }),
            removeItem: key => cookies.remove(key)
        },
    }),
    createPersistedState({
        key: process.env.PERSISTENT_COOKIE_NAME,
        paths: [
            'user',
        ],
    })
];

然后像这样使用它:

const Store = new Vuex.Store({
    ...
    plugin: persistedStates;
    ...
})

现在我还需要添加pathify插件。我试过

plugin: [persistedStates, pathify.plugin]

但它不起作用并返回错误(vuex.esm.js?94e4:368 Uncaught (in promise) TypeError: plugin is not a function)。我错过了什么?

标签: javascriptvuex

解决方案


Vuex 文档非常简单: https ://vuex.vuejs.org/guide/plugins.html

const myPlugin = store => {
  // called when the store is initialized
  store.subscribe((mutation, state) => {
    // called after every mutation.
    // The mutation comes in the format of `{ type, payload }`.
  })
}

const store = new Vuex.Store({
  // ...
  plugins: [myPlugin]
})

推荐阅读