本文主要是介绍Vue2:Vuex中使用mapState和mapGetters,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、情景说明
前面的Vuex
案例中
我们在使用state
中的变量或者getter
中的变量时
使用插值语法,写法如下:
<h1>当前求和为:{{$store.state.sum}}</h1><h1>当前求和放大10倍为:{{$store.getters.bigSum}}</h1><h3>我在{{$store.state.school}},学习{{$store.state.subject}}</h3>
我们会发现,重复写了前缀:$store.state
和$store.getters
那么,当业务一旦复杂,变量多起来,这边的编码效率就低了很多。
这里,mapState
和mapGetters
配合computed
来解决这个问题。
使Vuex
编码简便化!
二、案例
index.js
中的state
和getter
配置
//准备state 用于存储数据
const state = {sum:0, //当前的和school:'中国',subject:'Vue'
};//准备getters——用于加工state中的数据
const getters = {bigSum(state){return state.sum*10}
}
vc
中引入mapState,mapGetters
import {mapState,mapGetters} from 'vuex'
vc
中的computed
里使用mapState,mapGetters
两种写法,根据具体情况来决定使用
//借助mapState生成计算属性,从state中读取数据。(对象写法)//...mapState({he:'sum',xuexiao:'school',xueke:'subject'}),//借助mapState生成计算属性,从state中读取数据。(数组写法)...mapState(['sum','school','subject']),//借助mapGetters生成计算属性,从getters中读取数据。(对象写法)//...mapGetters({bigSum:'bigSum'})//借助mapGetters生成计算属性,从getters中读取数据。(数组写法)...mapGetters(['bigSum'])
vc
中html
代码改写
经过以上配置,就不用再写一大堆前缀了
<h1>当前求和为:{{sum}}</h1><h3>当前求和放大10倍为:{{bigSum}}</h3><h3>我在{{school}},学习{{subject}}</h3>
这篇关于Vue2:Vuex中使用mapState和mapGetters的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!