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;
    }
  },
  // 其他组件选项...
};
相关推荐
zwjapple4 小时前
docker-compose一键部署全栈项目。springboot后端,react前端
前端·spring boot·docker
像风一样自由20206 小时前
HTML与JavaScript:构建动态交互式Web页面的基石
前端·javascript·html
aiprtem7 小时前
基于Flutter的web登录设计
前端·flutter
浪裡遊7 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
why技术7 小时前
Stack Overflow,轰然倒下!
前端·人工智能·后端
幽络源小助理7 小时前
SpringBoot基于Mysql的商业辅助决策系统设计与实现
java·vue.js·spring boot·后端·mysql·spring
GISer_Jing7 小时前
0704-0706上海,又聚上了
前端·新浪微博
止观止7 小时前
深入探索 pnpm:高效磁盘利用与灵活的包管理解决方案
前端·pnpm·前端工程化·包管理器
whale fall7 小时前
npm install安装的node_modules是什么
前端·npm·node.js
烛阴7 小时前
简单入门Python装饰器
前端·python