vuex study第二节state访问状态对象

上一节我们是直接用 $store.state.count 来访问store状态的,现在我们是想处理一下,然后直接用 count 来调用:
第一种方法:用vue的computed计算属性,在Count.vue

<template>
    <div>
        <h1>{{ msg }}</h1>
        <!--直接引用store里的数据-->
        <h2>{{ $store.state.count }}--{{ count }}</h2>
        <!--提交store里mutations内的方法-->
        <button @click="$store.commit('add')">+</button>
        <button @click="$store.commit('reduce')">-</button>
    </div>
</template>

<script>
    import store from '@/vuex/store'
    export default {
        data(){
            return {
                msg: 'Hello Vuex!'
            }
        },
        computed:{
            count(){
//注意要加this
                return this.$store.state.count;
            }
        },
        //将store添加到实例
        store
    }
</script>

<style>
</style>

这里写图片描述
第二种方法:通过vuex的mapState

<script>
    import store from '@/vuex/store'
    //注意mapState要加 {}
    import { mapState } from 'vuex'
    export default {
        data(){
            return {
                msg: 'Hello Vuex!'
            }
        },
        //同样是计算属性
        computed:mapState({
            //es6写法
            count:state => state.count
        }),
        //将store添加到实例
        store
    }
</script>

其他和第一种一样

第三种:

<script>
    import store from '@/vuex/store'
    //注意mapState要加 {}
    import { mapState } from 'vuex'
    export default {
        data(){
            return {
                msg: 'Hello Vuex!'
            }
        },
        computed:mapState(['count']),
        //将store添加到实例
        store
    }
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值