首页 > 解决方案 > 是否可以从 Vuex 中导入的本地函数调用?

问题描述

我有一个名为的简单文件_mixin.js,其中包括:

const mutations = {
    _set(state, data) {       
        for (let key in data) {
            if (key in state) {
                state[key] = data[key];
            }
        }
    },

    _reset(state) {
        const s = initialState();

        Object.keys(s).forEach(key => {
            state[key] = s[key];
        });
    }
};

export default {
    mutations
};

我想要做的是在所有现有模块突变之间共享这两种方法,如下所示:

import _MIXINS from 'store/modules/_mixins';

function initialState() {
    return {
        id: null,
        email: null,
        password: null,
        name: null,
    };
}

const state = initialState();


const mutations = {
    ..._MIXINS.mutations,

    setId(state, id) {
        state.id = id;
    }
};

问题是浏览器说它找不到函数initialState,因为它不在同一个文件中。

标签: javascriptvuexvuex-modules

解决方案


这样做:

// sharedLogic.js

export function initialState () {
    // your logic
}

// 存储模块

import { initialState } from '<pathTo sharedLogic.js>'
const state = initialState();

// 混合模块

import { initialState } from '<pathTo sharedLogic.js>'
const mutations = {
   ...
    _reset(state) {
        const s = initialState();

        Object.keys(s).forEach(key => {
            state[key] = s[key];
        });
    }
};

推荐阅读