Vuex Actions的一次异步请求

Actions

image-20201205145300032

根据流程图得知,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的异步操作

posted @ 2020-12-05 15:27  Ssinoo団子  阅读(1136)  评论(0编辑  收藏  举报