vue项目中使用vuex管理公共状态2-vuex异步(actions)

  • 当多个页面使用同一个异步请求得到的数据, 就可以使用actions
  • 可以理解为缓存, 减少ajax请求次数, 减少使用流量

定义 actions

  • 定义一个叫 getCinemaList 的异步方法

store目录下的index.js中:

import Vue from 'vue'
import Vuex from 'vuex'
import http from '@/util/http'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cityId: 310100,
    cityName: '上海',

    cinemaList: []
  },
  // 集中式修改状态
  mutations: {
    setCinemaList (state, item) {
      state.cinemaList = item
    }
  },
  // 异步
  actions: {
    getCinemaList (store, cityId) {
      return http({
        url: `/gateway?cityId=${cityId}&ticketFlag=1&k=4902196`,
        headers: {
          'X-Host': 'mall.film-ticket.cinema.list'
        }
      }).then(res => {
        // console.log(res.data)
        // 调用mutations内的setCinemaList方法, 把请求后得到的数据赋值给cinemaList
        store.commit('setCinemaList', res.data.data.cinemas)
      })
    }
  },
  modules: {
  }
})

使用- dispatch

 this.$store.dispatch('getCinemaList', this.$store.state.cityId)

具体代码

<script>
// import http from '@/util/http'
import BetterScroll from 'better-scroll'
import Vue from 'vue'

export default {
  mounted () {
    console.log('全局状态getCinemaList的值:',this.$store.state.getCinemaList)
    // 动态获取影院列表所占用的高度
    this.height = document.documentElement.clientHeight - 100 + 'px'

    if (this.$store.state.cinemaList.length === 0) {
      // vuex 异步流程
      this.$store.dispatch('getCinemaList', this.$store.state.cityId).then(res => {
        this.$nextTick(() => {
          new BetterScroll('.cinema', {
            mouseWheel: true, // 解决better-scroll在PC端使用,鼠标无法实现滚动的解决
            scrollbar: { // 滚动条, 要加相对位置
              fade: true
            }
          })
        })
      })
    } else {
      console.log('使用缓存')
      this.$nextTick(() => {
        new BetterScroll('.cinema', {
          mouseWheel: true, // 解决better-scroll在PC端使用,鼠标无法实现滚动的解决
          scrollbar: { // 滚动条, 要加相对位置
            fade: true
          }
        })
      })
    }
  }
}
</script>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值