vuex

什么是Vuex

vuex是一个专门为vue.js设计的集中式状态管理架构。将状态管理单独拎出来,应用统一的方式进行处理,在后期维护的过程中数据的修改和维护就变得简单而清晰了。Vuex采用和Redux类似的单向数据流的方式来管理数据。用户界面负责触发动作(Action)进而改变对应状态(State),从而反映到视图(View)上。如下图所示:

使用vuex

安装vuex

控制台  : npm install vuex --save         需要注意的是这里一定要加上 –save,因为你这个包我们在生产环境中是要使用的。

引入:

 

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(vuex);

入门小Demo

在 src 新建文件vuex(不是必须的),在里面新建文件store.js 文件引入vuex

 

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const state = {   //声明问状态对象
    count:1
};

const mutations= {     //声明改变状态的方法
    add(state){
        state.count++;
    },
    reduce(state){
        state.count--;
    }
    
}
//用export default 封装代码,让外部可以引用。
export default new Vuex.Store({   
    state,
    mutations
})

新建一个vue的模板,位置在components文件夹下,名字叫count.vue。在模板中我们引入我们刚建的store.js文件,并在模板中用{{$store.state.count}}输出count 的值。

<template>
     <div>
        <h2>{{msg}}</h2>
        <hr/>
        <h3>{{$store.state.count}}</h3>
        <p><button @click="$store.commit('add')">+</button></p>
        <p><button @click="$store.commit('reduce')">-</button></p>
    </div>
</template>

<script>
    import store from '@/vuex/store'
    export default{
        data(){
            return{
                msg:'Hello Vuex',
 
            }
        },
        store
        
    }
</script>

在 路由里面引入这个组件

import Count from '@/components/Count'
{ path:'/count', component: Count }

 

核心的部分进行说明

 State负责存储整个应用的状态数据,一般需要在使用的时候在跟节点注入store对象,(main.js)后期就可以使用this.$store.state直接获取状态

//store为实例化生成的
import store from './store'

new Vue({
  el: '#app',
  store,
  render: h => h(App)
})

这个store可以理解为一个容器,包含着应用中的state等。实例化生成store的过程是:

const mutations = {...};
const actions = {...};
const state = {...};

Vuex.Store({
  state,
  actions,
  mutation
});

后续在组件中使用的过程中,如果想要获取对应的状态你就可以直接使用this.$store.state获取,当然,也可以利用vuex提供的mapState辅助函数将state映射到计算属性中去,

 

//我是组件
import {mapState} from 'vuex'

export default {
  computed: mapState({
    count: state => state.count
  })
}

这样直接就可以在组件中直接使用了。

state状态对象赋值给内部对象,也就是把stroe.js中的值,赋值给我们模板里data中的值。我们有三种赋值方式,我们一个一个来学习一下。

1.通过computed的计算属性直接赋值 (组件页面)

<script>
    import store from '@/vuex/store'
    export default{
        data(){
            return{
                msg:'Hello Vuex',
            }
        },
        computed:{
            count(){
                return this.$store.state.count
            }
        }   
    }
</script>

这里需要注意的是return this.$store.state.count这一句,一定要写this,要不你会找不到$store的。这种写法很好理解,但是写起来是比较麻烦的,

2.通过mapState的对象来赋值      //mapState 像当与映射

我们首先要用import引入mapState。 然后还在computed计算属性里写如下代码:

import {mapState} from 'vuex';     //注意mapState 写法

computed:mapState({
        count:state=>state.count
 })
//这里我们使用ES6的箭头函数来给count赋值。   等同于:
count:function(state){return state.count}

3.通过mapState的数组来赋值       

这个算是最简单的写法了,在实际项目开发当中也经常这样使用。

posted @ 2017-09-25 16:19  模糊的星空  阅读(128)  评论(0)    收藏  举报