Vue之调用store的action(包含getter调用)

文章目录

Vue之调用store的action(包含getter调用)

调用store的action

方法一:Promise 链式调用

c 复制代码
this.$store.dispatch('actionOne')
  .then(() => {
    return this.$store.dispatch('actionTwo');
  })
  .then(() => {
    return this.$store.dispatch('actionThree');
  })
  .catch(error => {
    // 处理错误
    console.error(error);
  });

这种方式会依次触发这三个 action,并在每个 action 完成后再触发下一个 action。

方法二:async/await

c 复制代码
async someMethod() {
  try {
    await this.$store.dispatch('actionOne');
    await this.$store.dispatch('actionTwo');
    await this.$store.dispatch('actionThree');
  } catch (error) {
    // 处理错误
    console.error(error);
  }
}

使用 async/await 可以让代码看起来更像同步操作,但依然是异步执行。这样的方式也可以让后续的 action 等待前一个 action 完成后再执行。

方法三:Promise.all()同时执行

c 复制代码
Promise.all([this.$store.dispatch('actionOne'), this.$store.dispatch('actionTwo'), this.$store.dispatch('actionThree')])
  .then(results => {
    // 所有异步操作都成功完成,results 是包含每个异步操作结果的数组
    console.log(results);
  })
  .catch(error => {
    // 至少有一个异步操作失败
    console.error(error);
  });

总结:选择哪种方式取决于你的需求,以及这些 action 之间是否有依赖关系。如果它们之间是独立的,可以同时执行,那么使用 Promise.all() 可能更合适。如果需要按顺序执行,可以使用 Promise 链式调用或 async/await。

调用store的getter

方法一:this.$store.getters调用

如果你在 Vue.js 组件中的 methods 部分想要调用 Vuex store 中的 getter,你可以通过使用 this.$store.getters 来访问。假设你有一个名为 getCityList 的 getter,你可以这样在组件的 methods 中调用它:

c 复制代码
export default {
  methods: {
    someMethod() {
      // 调用 Vuex store 中的 getCityList getter
      const cityList = this.$store.getters.getCityList;
    }
  },
  // 其他组件选项...
};

在上面的例子中,this.$store.getters.getCityList 就是访问 Vuex store 中 getCityList getter 的方法。

方法二:mapGetters调用

确保你使用的 getter 名称和 Vuex store 中的命名一致。如果你在使用模块化的 Vuex store,也需要考虑模块的命名空间。在这种情况下,你可以使用 mapGetters 辅助函数,这将自动处理命名空间。

c 复制代码
import { mapGetters } from 'vuex';

export default {
  computed: {
    // 使用 mapGetters 辅助函数将两个 getter 映射到计算属性
    ...mapGetters(["getCityList", "getCountryList"])
  },
  methods: {
    someMethod() {
      // 直接访问映射后的计算属性
      const cityList = this.getCityList;
      const countryList = this.getCountryList;
    }
  },
  // 其他组件选项...
};

上面的代码假设你已经在组件中使用 mapGetters 映射了 getCityList和getCountryList的getter。

示例代码:

src/store/modules/city.js

c 复制代码
//接口
import { getCityListAPI } from "@/api/commonAPI.js";

const state = {
  cityList: []
}

const getters = {
  getCityList: state => {
    var list;
    //先从session中获取,获取不到再从state里获取
    if (sessionStorage.getItem('cityList')) {
      list = JSON.parse(sessionStorage.getItem('cityList'));
    } else {
      list = state.cityList;
    }
    return list;
  }
}

const mutations = {
  ["SET_CITY_INFO"](state, data) {
    state.cityList = data === null ? {} : data;
    //设置进session中
    sessionStorage.setItem('cityList',JSON.stringify(data))
  }
}

const actions = {
  //调用接口获取地市放进session中
  setCityList({commit}) {
    return new Promise(resolve => {
      getAllCityListAPI().then(res => {
        commit("SET_CITY_INFO", res);
        resolve()
      });
    })
  }
}

export default {
  state,
  getters,
  mutations,
  actions
};

src/store/index.js

c 复制代码
import Vue from "vue";
import Vuex from "vuex";
import createPersistedState from "vuex-persistedstate";
import city from "./modules/city";

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    city
  },
  plugins: [createPersistedState({ storage: window.sessionStorage })]
});

调用action

c 复制代码
Promise.all([this.$store.dispatch('setCityList'))
  .then(results => {
    console.log("获取地市列表信息----------------");
  })
  .catch(error => {
    // 至少有一个异步操作失败
    console.error(error);
  });

调用getter

c 复制代码
export default {
  methods: {
    someMethod() {
      // 调用 Vuex store 中的 getCityList getter
      const cityList = this.$store.getters.getCityList;
    }
  },
  // 其他组件选项...
};
相关推荐
Zoey的笔记本10 分钟前
「支持ISO27001的GTD协作平台」数据生命周期管理方案与加密通信协议
java·前端·数据库
北辰alk11 分钟前
Vue 的 nextTick:破解异步更新的玄机
vue.js
北辰alk11 分钟前
Vue 技巧揭秘:一个事件触发多个方法,你竟然还不知道?
vue.js
北辰alk24 分钟前
Vue 中 computed 和 watch 的深度解析:别再用错了!
vue.js
奔跑的呱呱牛38 分钟前
geojson-to-wkt 坐标格式转换
javascript·arcgis
C_心欲无痕1 小时前
Docker 本地部署 CSR 前端项目完整指南
前端·docker·容器
康一夏2 小时前
React面试题,封装useEffect
前端·javascript·react.js
Full Stack Developme2 小时前
Redis 持久化 备份 还原
前端·chrome
猪猪拆迁队2 小时前
2025年终总结-都在喊前端已死,这一年我的焦虑、挣扎与重组:AI 时代如何摆正自己的位置
前端·后端·ai编程
❆VE❆2 小时前
WebSocket与SSE深度对比:技术差异、场景选型及一些疑惑
前端·javascript·网络·websocket·网络协议·sse