Vuex的使用

安装

直接下载/CDN引用

<script src="/path/to/vue.js"></script>
<script src="/path/to/vuex.js"></script>

npm


  npm install vuex --save-dev

Yarn


  yarn add vuex

在一个模块打包系统中,必须显示地通过Vue.use()来安装Vuex


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

  Vue.use(Vuex)

Vuex是一个专为Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

使用例子如下:

main.js

    
  import store from './store'

  new Vue({
      store,//注入组件当中
      el: '#app',
      render: h => h(App)
  })

store.js


import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);

var state = {
    count: 10
};

const mutations = {
    increment(state) { //处理状态(数据)变化
        state.count++;
    },
    decrement(state) {
        state.count--;
    }
};

const actions = {
    increment: ({ //处理你要干什么,异步请求,判断,流程控制
        commit
    }) => {
        commit('increment')
    },
    decrement: ({
        commit
    }) => {
        commit('decrement');
    },
    clickOdd: ({
        commit,
        state
    }) => {
        if (state.count % 2 == 0) {
            commit('increment')
        }
    },
    clickAsync: ({
        commit
    }) => {
        new Promise((resolve) => {
            setTimeout(function() {
                commit('increment');

                resolve();
            }, 1000);
        });
    }
};

const getters = {
    count(state) {
        return state.count;
    },
    getOdd(state) {
        return state.count % 2 == 0 ? '偶数' : '奇数';
    }
};


//需要导出Store对象
export default new Vuex.Store({
    state,
    mutations,
    actions,
    getters
});

App.vue


<template>
  <div id="app">
    <h3>welcome vuex-demo</h3>
    <input type="button" value="增加" @click="increment">
    <input type="button" value="减少" @click="decrement">
    <input type="button" value="偶数才能点击+" @click="clickOdd">
    <input type="button" value="点击异步" @click="clickAsync">

    <div>
      现在数字为: {{count}}, 它现在是 {{getOdd}}
    </div>
  </div>
</template>

<script>
  import {mapGetters, mapActions} from 'vuex'

  export default{
    computed:mapGetters([
      'count',
      'getOdd'
    ]),
    methods:mapActions([//分发action
      'increment',//映射 this.increment() 为 this.$store.dispatch('increment')
      'decrement',
      'clickOdd',
      'clickAsync'
    ])
  }
</script>


posted @ 2017-05-10 16:38  Leiwensu  阅读(247)  评论(1)    收藏  举报