Actions

Vuex Actions的一次异步请求

根据流程图得知,actions是接受后端api的,进行异步请求,获取到的数据 要通过commit提交给mutation,mutation才能修改state中的数据,

案例: 请求卖座的api 通过action

1,首先先判断页面是否拥有数据,没有的话,使用action进行异步请求

if(this.$store.state.cinemaList.length === 0 ){
      //vuex 异步
      this.$store.dispatch('getCinemaList',this.$store.state.cityId)

dispatch是流程图中,组件内提交给action的方法

括号传,定义的方法,和需要传的值

2.在store文件中

actions: {
    getCinemaList(store,cityId){
      return http({
        url: `https://m.maizuo.com/gatewaycityId=${cityId}&ticketFlag=1&k=7668767`,
        headers: {
          "X-Host": "mall.film-ticket.cinema.list",
        },
      })

return:是因为是promise对象

括号,一个是store自身的形参,传的值

3,

 //异步
  actions: {
    getCinemaList(store,cityId){
      return http({
        url: `https://m.maizuo.com/gateway?cityId=${cityId}&ticketFlag=1&k=7668767`,
        headers: {
          "X-Host": "mall.film-ticket.cinema.list",
        },
      }).then((res) => {
        // console.log(res.data);
        store.commit('setCinemaList',res.data.data.cinemas)
      });
    }
  },

根据流程图,将请求的数据给mutation,通过commit方法

4,在mutation中,修改state中cinema的数据

 setCinemaList(stata,cinemaList){
      stata.cinemaList = cinemaList
    }

这样就完成了一次Vuex的异步操作

相关文章:

  • 2022-01-18
  • 2021-11-07
  • 2021-11-07
  • 2021-05-29
  • 2021-10-19
  • 2022-03-11
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-14
  • 2022-12-23
  • 2021-12-20
  • 2021-11-17
相关资源
相似解决方案