vue项目中的js文件使用vuex

使用场景:假设有一个接口,需要在很多页面获取一遍并且将接口的返回值保存起来,这样就能使用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;


// 如果是 nuxt 写法应为:
// export default new Vuex.Store({
//  modules: {
//    firmModule,
//  },
// });

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: {}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值