使用场景:假设有一个接口,需要在很多页面获取一遍并且将接口的返回值保存起来,这样就能使用vuex,将值保存在vuex中
实现:vuex中新建firmModule.js文件,编写存储值的代码,utils/getFirmData.js用来调接口获取值并将值存储在vuex中,xxx.vue中调取getFirmData.js中的方法,并且在watch中监听vuex的值实现给xxx.vue的form赋值
store/modules/firmModule.js
const state = {
firmData: {
firmId: undefined,
firmName: undefined,
},
};
const mutations = {
SET_FIRM_DATA(state, firmData) {
state.firmData = firmData;
},
};
const actions = {
setFirmData({ commit }, firmData) {
commit("SET_FIRM_DATA", firmData);
},
};
export default {
namespace: true,
state,
mutations,
actions,
};
store/index.js
import Vue from "vue";
import Vuex from "vuex";
import firmModule from "@/store/modules/firmModule";
Vue.use(Vuex);
const store = new Vuex.Store({
modules: {
firmModule,
},
});
export default store;
utils/getFirmData.js
/**
* @Event 获取企业信息
* @description: 最终数据存储到vuex中 store.state.firmModule.firmData
* @author: mhf
* @time: 2023-11-16 21:41:05
**/
import { queryUserId } from "@/api/enterpriseManage/riskControl.js"; // 接口
import { isEmptyArray } from "@/utils/publicFun"; // 判断是否是空数组
import store from "@/store";
export async function getFirmData() {
try {
const user = localStorage.getItem('user');
if (!user) {
throw new Error('无法获取用户信息');
}
const userId = JSON.parse(user).user.userId;
const res = await queryUserId({ userId })
if (isEmptyArray(res.data)) {
throw new Error('查询结果为空')
}
await store.dispatch('setFirmData', res.data[0])
} catch (error) {
throw new Error('失败:' + error)
}
}
// isEmptyArray方法如下:
/**
* @Event 判断是否是空数组
* @description:
* @author: mhf
* @time: 2023-11-16 17:26:31
**/
export function isEmptyArray(arr) {
if (Object.prototype.toString.call(arr) !== "[object Array]") return;
return arr.length === 0;
}
xxx.vue
import { getFirmData } from "@/utils/getFirmData";
// 监听vuex中的数据给formData赋值
watch: {
"$store.state.firmModule.firmData"(obj) {
this.$set(this.formData, "firmName", obj.firmName);
this.$set(this.formData, "firmId", obj.id);
}
},
created() {
getFirmData();
},
注意 eslint检测async await配置如下
.eslintrc.js
// ESlint 检查配置
module.exports = {
root: true,
parserOptions: {
parser: 'babel-eslint',
sourceType: 'module',
"ecmaVersion": 2020, // 需要此项
},
env: {
browser: true,
node: true,
es6: true
},
extends: [],
// add your custom rules here
// it is base on https://github.com/vuejs/eslint-config-vue
rules: {}
}