1.当需要从store中获取一些state变异后的状态时,可以使用getters,如获取state中的counter的平方值
state:{
counter:100
},
getters:{
powerCounter(state){
return state.counter * state.counter
}
}
<h2>{{$store.getters.powerCounter}}</h2>
获取超过20岁的学生:
store
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
students:[
{id:1,name:'xiaoming',age:18},
{id:2,name:'dahei',age:21},
{id:3,name:'qiaodan',age:40},
]
},
getters:{
studentsMore20(state){
return state.students.filter(s=>s.age>20)
}
}
})
export default store
App.vue
<template>
<div id="app">
<div>{{ $store.getters.studentsMore20 }}</div>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {}
}
}
</script>
getters可以作为参数,供其它getters使用
获取上面代码中年龄大于20岁的长度
getters:{
studentsMore20(state){
return state.students.filter(s=>s.age>20)
},
studentMore20Length(state,getters){
return getters.studentsMore20.length
}
}
<div>{{ $store.getters.studentMore20Length }}</div>
当getters需要传递参数时,可以通过返回一个函数来接收参数
获取年龄大于某一参数的学生
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
students:[
{id:1,name:'xiaoming',age:18},
{id:2,name:'dahei',age:21},
{id:3,name:'qiaodan',age:40},
]
},
getters:{
studentMoreAge(state){
// return function(paramAge){
// return state.students.filter(s=>s.age>paramAge)
// }
return paramAge => state.students.filter(s=>s.age>paramAge)
}
}
})
export default store
<div>{{ $store.getters.studentMoreAge(21) }}</div>
mapGetters 辅助函数
mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性:
getters
export default {
powerCount(state) {
return state.counter * state.counter
},
addHello(state) {
return state.counter + 'hello'
}
}
store
import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
counter: 10
},
getters
})
export default store
App.vue
<template>
<div id="app">
<h2>{{ $store.state.counter }}</h2>
<div>{{power}}</div>
<div>{{add}}</div>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
name: 'App',
data () {
return {}
},
computed: {
// ...mapGetters(['powerCount', 'addHello'])
...mapGetters({
power: 'powerCount',
add: 'addHello'
})
}
}
</script>
mapGetters 有两种写法 ,一种是数组,另一种是对象,对象的方式可以重新命名计算属性的名称
网友评论