当前位置: 首页 > news >正文

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

文章目录

  • Vue之调用store的action(包含getter调用)
    • 调用store的action
      • 方法一:Promise 链式调用
      • 方法二:async/await
      • 方法三:Promise.all()同时执行
    • 调用store的getter
      • 方法一:this.$store.getters调用
      • 方法二:mapGetters调用
    • 示例代码:

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

调用store的action

方法一:Promise 链式调用

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

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()同时执行

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 中调用它:

export default {methods: {someMethod() {// 调用 Vuex store 中的 getCityList getterconst cityList = this.$store.getters.getCityList;}},// 其他组件选项...
};

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

方法二:mapGetters调用

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

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

//接口
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

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

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

调用getter

export default {methods: {someMethod() {// 调用 Vuex store 中的 getCityList getterconst cityList = this.$store.getters.getCityList;}},// 其他组件选项...
};
http://www.lryc.cn/news/274076.html

相关文章:

  • 蟹目标检测数据集VOC格式400张
  • PyTorch中常用的工具(4)Visdom
  • Linux(ubuntu)下git / github/gitee使用
  • 回归预测 | MATLAB实OOA-LSTM基于鱼鹰优化算法优化长短期记忆网络的多输入单输出数据回归预测模型 (多指标,多图)
  • 2023年工作初体验
  • PostgreSQL 作为向量数据库:入门和扩展
  • 亚信安慧AntDB数据库:企业核心业务系统数据库升级改造的可靠之选
  • CommonJS 和 ES6 Module:一场模块规范的对决(上)
  • python快速实现简易电子音乐盒(电子钢琴)
  • 详解bookkeeper AutoRecovery机制
  • 使用 Ubuntu 20.04 进行初始服务器设置
  • 【SpringCloud】6、Spring Cloud Gateway路由配置
  • pdf转换成word怎么转?一篇文章教你轻松搞定
  • 【中南林业科技大学】计算机组成原理复习包括题目讲解(超详细)
  • 恭喜 Databend 上榜 2023 开源创新榜「优秀开源项目 」
  • 网络连通性批量检测工具
  • 2023高级人工智能期末总结
  • Oracle数据库迁移所有文件到新挂载磁盘路径
  • 基于YOLOv7算法的高精度实时安全背心目标检测识别系统(PyTorch+Pyside6+YOLOv7)
  • Mac——VsCode使用格式化工具进行整理和格式化
  • 73.乐理基础-打拍子-还原号、临时变音记号在简谱中的规则
  • 一款超酷的一体化网站测试工具:Web-Check
  • MockServer简单使用记录
  • AI+金融:大模型引爆金融科技革命
  • 数据库(二)实验一:MySQL数据库的C/S模式部署
  • RLHF几大常用框架实践对比(trlx、deepspeedchat、colossalaichat)
  • Oracle/Myql批量操作
  • 关于一个web站点的欢迎页面
  • 1050. 鸣人的影分身(dp划分)
  • 51单片机点灯入门教程——2. 呼吸灯效果