脚本宝典收集整理的这篇文章主要介绍了Vue 教程第十五 篇—— Vuex 之 getter,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
getters 可以理解为 vuex 中的 computed,和 vue 中的 computed 类似,都是用来计算 state 然后生成新的数据 ( 状态 ) 的。
在上面的案例当中,如果想得到的 state 最终为一个带了币种的金额,只要给一个统一的出口,返回统一的数据模式。
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
let state = {
count: 0
}
let getters = {
total: state => {
return '$' + state.count;
}
}
let mutations = {
increment(_state, n){
_state.count += n || 1;
},
decrement(){
state.count -= 1;
}
}
const store = new Vuex.Store({
state,
getters,
mutations
})
export default store
<h3>count-{{$store.getters.total}}</h3>
如果上面的方法想改变货币符号,那就要通过传参方式来解决
let getters = {
total: (state) => (symbol) => {
return (symbol || '$') + state.count;
}
}
<h3>count-{{$store.getters.total('¥')}}</h3>
<template>
<div>
<h3>count-{{total('¥')}}</h3>
</div>
</template>
<script>
import common from '../../common/common.js'
import {mapState, mapMutations, mapGetters} from 'vuex';
export default {
computed: {
...mapGetters([
'total'
])
}
}
</script>
<template>
<div>
<h3>count-{{amount('¥')}}</h3>
</div>
</template>
<script>
import common from '../../common/common.js'
import {mapState, mapMutations, mapGetters} from 'vuex';
export default {
computed: {
...mapGetters({
amount: 'total'
})
}
}
</script>
以上是脚本宝典为你收集整理的Vue 教程第十五 篇—— Vuex 之 getter全部内容,希望文章能够帮你解决Vue 教程第十五 篇—— Vuex 之 getter所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。