Vue 教程第十五 篇—— Vuex 之 getter

发布时间:2019-05-17 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Vue 教程第十五 篇—— Vuex 之 getter脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

getter

getters 可以理解为 vuex 中的 computed,和 vue 中的 computed 类似,都是用来计算 state 然后生成新的数据 ( 状态 ) 的。

在上面的案例当中,如果想得到的 state 最终为一个带了币种的金额,只要给一个统一的出口,返回统一的数据模式。

简单实现

Store.js
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

getter 通过属性访问

<h3>count-{{$store.getters.total}}</h3>

getter 通过方法访问

如果上面的方法想改变货币符号,那就要通过传参方式来解决

let getters = {
    total: (state) => (symbol) => {
        return (symbol || '$') + state.count;
    }
}
<h3>count-{{$store.getters.total('¥')}}</h3>

mapGetters 辅助函数

<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>

mapGetters 辅助函数之别名

<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,请注明来意。