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

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 getter
      const 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 getter
      const cityList = this.$store.getters.getCityList;
    }
  },
  // 其他组件选项...
};
  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值