您现在的位置:首页 >> 前端 >> 内容

vuex study之state访问状态对象

时间:2018/1/2 11:10:13 点击: 25

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

上一节我们是直接用 $store.state.count 来访问store状态的,现在我们是想处理一下,然后直接用 count 来调用:

第一种方法:用vue的computed计算属性,在Count.vue

<template>
    <p>
        <h1>{{ msg }}</h1>
        <!--直接引用store里的数据-->
        <h2>{{ $store.state.count }}--{{ count }}</h2>
        <!--提交store里mutations内的方法-->
        <button @click="$store.commit('add')">+</button>
        <button @click="$store.commit('reduce')">-</button>
    </p>
</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 study之state访问状态对象

第二种方法:通过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>

Tags:VU UE EX XS 
作者:网络 来源:z858466的博客
请选择您看到这篇文章时的心情: 已有0人表态:
0
0
0
0
0
0
0
0
惊讶 欠揍 支持 很棒 愤怒 搞笑 恶心 不解