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>

猜你喜欢

转载自blog.csdn.net/lxb_wyf/article/details/113610045