官網的定義vuex爲狀態管理模式,能夠集中管理組件的狀態。vue
假若有好幾個不一樣地方的組件視圖,須要顯示同一個數據源,當數據的狀態發生改變時,他們也要同時改變。若是使用傳參或者複製計算屬性來實現,是使代碼變得冗餘且難以維護。若是組件之間的關係不是父子關係也難以傳遞。vuex
在怎麼用vuex以前,先了解它有什麼。
vuex的核心是store對象,store裏面能夠保存多個state,也就是狀態。在根元素建立new Vue({store})的時候引入store,這樣就能夠全局使用單例狀態樹,經過$store.state.來獲取。
mutation:保存改變狀態方法,必須是同步的。commit('func')的方式來改變
getter:用來派生出另外一種狀態,例如說判斷count是奇數仍是偶數
actions:與mutation相似,但本質是提交mutation,區別在於能夠異步請求npm
試想一下,假如一個應用好幾個地方都會有判斷狀態count是奇偶數的需求,若是在每個組件computed:{ evenOrOdd:this.$store.state.count%2===0?'even':'odd' },是否是有一些多餘呢,mapGetters能夠把getter裏的計算屬性映射到computed中,讓咱們省去了這一部分工做,mapActions同理。異步
1.安裝依賴 npm install vuex學習
2.將store單獨拎出來管理,建立state,mutation,actions,getters。
定義好狀態和方法後,在new Vuex.Store({state,mutation,actions,getters})this
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex) //狀態對象 const state = { count:0, times:0 } //改變狀態的方法 const mutations = { increment(state){ state.count++ state.times++ }, decrement(state){ state.count-- state.times++ } } // 異步執行 const actions = { increment:({commit}) =>commit('increment'), decrement:({commit}) =>commit('decrement'), isEvenorOdd({commit,state}){ if(state.count%2===0){ commit('increment'); } } } const getters = { evenOrOdd:state => state.count%2===0?'even':'odd' } export default new Vuex.Store({ state, getters, actions, mutations })
3.建立有狀態管理的counter.vue組件,經過$store.state....能夠獲取到狀態對象spa
<template> <div class=""> <span @click="decrement">-</span> <span> {{$store.state.count}} </span> <span @click="increment">+</span> <button type="button" name="button" @click="isEvenorOdd">if count is even</button> <p>click {{$store.state.times}} times,count is {{evenOrOdd}}</p> </div> </template> <script> import { mapGetters,mapActions } from 'vuex' export default { computed:{ ...mapGetters({ 'evenOrOdd':'evenOrOdd' }) }, methods:mapActions([ 'increment', 'decrement', 'isEvenorOdd' ]) } </script>
4.在入口文件index.js增長store對象code
new Vue({ router:router, store, render:(h)=> h(App) }).$mount(root)
實現效果router
每次點擊次數都會累加,count改變,會判斷出count是奇數仍是偶數
當count爲偶數時 if count is even 能夠點擊對象