【问题标题】:Is it possible to call local functions from imported in Vuex?是否可以从 Vuex 中导入的本地函数调用?
【发布时间】:2020-03-31 16:25:34
【问题描述】:

我有一个名为_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,因为它不在同一个文件中。

【问题讨论】:

  • 需要将函数导入到其他模块,但是完全可以在vuex中导入和使用本地函数。
  • @Eggon 你能举个例子吗?

标签: javascript vuex vuex-modules


【解决方案1】:

就这样吧:

//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];
        });
    }
};

【讨论】:

  • 问题是initialState在每个文件中都是唯一的,如果所有文件都有一个则mixin
  • 很抱歉,但在这种情况下,我不再理解您的问题了。您写道找不到initialState(它不能因为它没有在_mixin.js 中定义)。所以我想你想在两个模块中使用相同的功能。但是现在你写道你想要不同的?那么另一个的定义在哪里呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-17
  • 1970-01-01
  • 2015-05-22
相关资源
最近更新 更多