一、Getter
Getter用于对Store中的数据进行加工处理形成新的数据。
- Getter用于对Store中的数据进行加工处理形成新的数据,类似Vue的计算属性。
- Store中数据发生变化时,Getter中的数据也会随之变化。
- 【getter不会修改store中的原数据,只是对其进行包装】
二、实践-触发getters的两种方式
- 改动store/index.js——定义getters
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
add (state) {
state.count++
},
addN (state, step) {
setTimeout(() => {
state.count += step
}, 1000)
},
sub (state) {
state.count--
},
subN (state, step) {
state.count -= step
}
},
actions: {
addAsync (context) {
setTimeout(() => {
context.commit('add')
}, 1000)
},
addNAsync (context, step) {
setTimeout(() => {
context.commit('addN', step)
}, 1000)
},
subAsync (context) {
setTimeout(() => {
context.commit('sub')
}, 1000)
},
subNAsync (context, step) {
setTimeout(() => {
context.commit('subN', step)
}, 1000)
}
},
// 定义getters
getters: {
showNum (state) {
return '当前最新的count值为【' + state.count + '】'
}
}
})
- 改动Addition组件——实践第一种方式:
$store.getters
触发getters
<template>
<div>
<!-- <p>当前count的值为:{{ $store.state.count}}</p> -->
<!-- 插值表达式配合$store应用getters -->
<h3>{{ $store.getters.showNum }}</h3>
<button @click="handleAdd()">+1</button>
<button @click="handleAddN()">+N</button>
<button @click="$store.dispatch('addAsync')">+1 Async</button>
<button @click="$store.dispatch('addNAsync', 5)">+N Async</button>
</div>
</template>
<script>
export default {
data () {
return {}
},
methods: {
handleAdd () {
this.$store.commit('add')
},
handleAddN () {
this.$store.commit('addN', 3)
}
}
}
</script>
- 改动Subtraction组件——实践第二种方式:
mapGetters
触发getters
<template>
<div>
<!-- <p>当前count的值为:{{ count }}</p> -->
<!-- 3.应用。(showNum不是方法不要加括号) -->
<h3>{{ showNum }}</h3>
<button @click="handleSub()">-1</button>
<button @click="handleSubN()">-N</button>
<button @click="subAsync()">-1 Async</button>
<button @click="subNAsync(5)">-N Async</button>
</div>
</template>
<script>
// 1.从vuex中按需导入mapActions
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
export default {
data () {
return {}
},
computed: {
...mapState(['count']),
// 2.需要的getters函数映射为当前组件的computed
...mapGetters(['showNum'])
},
methods: {
...mapMutations(['sub', 'subN']),
...mapActions(['subAsync', 'subNAsync']),
handleSub () {
this.sub()
},
handleSubN () {
this.subN(3)
}
}
}
</script>