javascript - 是否可以从 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
,因为它不在同一个文件中。
解决方案
这样做:
// 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];
});
}
};
推荐阅读
- c# - 您没有调试 C# 的扩展,我们应该在 Marketplace 中找到 C# 扩展吗?
- c++ - 在抛出 'std::bad_alloc 的实例后调用终止
- c++ - 如何将变量从一个 cpp 文件传输到另一个
- python - Python脚本刷新文件夹中的所有excel文件
- java - 如何在具有来自控制器的自定义路径的 springboot 中提供静态资源?
- javascript - 从 index.html 请求 JSON - 这是从 url 获取数据的最佳方式
- screensaver - 删除恶作剧破解屏幕保护程序
- php - 我需要在 PHP 中使用哪种 SOAP 编码才不会丢失我的 xsi:type-attribute?
- python - 如何在 Python Odoo 中从网站获取输入到 field.integer()
- android - 如何在 Jetpack Compose 中创建椭圆渐变