vuex的新写法引入mapState省略$store.state

vuex的新写法:

state简写(映射):mapState

  • state里都是状态,所以mapState在computed中使用;
  • state映射也就是引入mapState,然后state可以简写
  • $store.state.状态  => 状态:前面的$store.state就省略不写了,直接写状态即可

    使用方法:

(1)在使用vuex的组件中先导入 mapState

import {mapState} from 'vuex'

(2)然后写计算属性computed

computed: {
    ...mapState(['cinemaList','cityName'])
  },
  • 含义:mapState(['cinemaList'])是一个函数调用,函数调用完会返回一个结果,结果是一个对象,再把对象用"..."展开;
  • 代码中的cinemaList是state里的状态,所以这个数组里面可以放其他的状态;
  • 这样状态在使用的时候都可以简写;

(3)然后在使用状态时,就直接 'this.状态' 就可以了,去掉 $store.state

$store.state.cinemaList => cinemaList

$store.state.cityName => cityName

既然state可以省略简写,actions、Mutations也能简写,

 


actions简写:mapActions映射

  • 因为actions里面放着的是函数,所以actions映射到组件的methods里;
  • 也就是说mapActions在methods中定义;
  • 使用方法:

(1)导入mapActions

import { mapActions } from 'vuex'

(2)在methods中映射 

methods: {
    ...mapActions(['getCinemaData'])//映射成本地的方法
}
  • 数组里的是actions中的方法,放在这里面,可以将vuex里的方法映射成本地的一个方法
  • 使用的时候就直接用 this. 方法替代了:this.$store.dispatch(方法)

(3)使用

this.$store.dispatch('getCinemaData', this.cityId) => this.getCinemaData(this.cityId)

mutations(简写):mapMutations映射

import { mapMutations } from 'vuex'
  methods: {
    ...mapMutations(['clearCinema'])
}
this.$store.commit('clearCinema') => this.clearCinema()

也可以:

 渲染列表时,列表cinemaList不能用