站内搜索:
首页 >> 前端 >> 内容
vuex study之state访问状态对象

时间:2018/1/2 11:10:13

上一节我们是直接用 $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>

  • 上一篇:Web前端工程化之VSCode+Git冲突问题解决办法
  • 下一篇:windows安装angular2-cli失败分析
  • 返回顶部