vuex是解決vue組件和組件間相互通訊而存在的,vuex理解起來稍微複雜,但一旦看懂則即爲好用:vue
安裝:vuex
npm install --save vuex
引入npm
import Vuex from 'vuex' import Vue from 'vue' Vue.use(Vuex)
vuex的幾個參數的介紹api
State 儲存初始化數據app
Getters 對State 裏面的數據二次處理(對數據進行過濾相似filter的做用)好比State返回的爲一個對象,咱們想取對象中一個鍵的值用這個方法異步
Mutations 對數據進行計算的方法所有寫在裏面(相似computed) 在頁面中觸發時使用this.$store.commit('mutationName') 觸發Mutations方法改變state的值函數
Actions 處理Mutations中已經寫好的方法 其直接觸發方式是 this.$store.dispatch(actionName)this
咱們先不急着瞭解更多先打印下Vuexurl
console.log(Vuex) //Vuex爲一個對象裏面包含 Vuex ={ Store:function Store(){}, mapActions:function(){}, // 對應Actions的結果集 mapGetters:function(){}, //對應Getters的結果集 mapMutations:function(){}, //對應Mutations的結果集 mapState:function(){}, //對應State的結果集 install:function install(){}, //暫時不作講解 installed:true //暫時不作講解 } //若是咱們只須要裏面的State時咱們能夠這樣寫 import { mapState } from 'vuex'; import { mapGetters, mapMutations } from 'vuex'; //若是須要引用多個時用這種方式處理
反覆看上面的內容是否是就豁然開朗了接下來咱們進行依次舉例和用官方的語言描述spa
State
State負責存儲整個應用的狀態數據,通常須要在使用的時候在跟節點注入store對象,後期就可使用this.$store.state直接獲取狀態
//store爲實例化生成的 import store from './store' new Vue({ el: '#app', store, render: h => h(App) })
這個store能夠理解爲一個容器,包含着應用中的state等。實例化生成store的過程是:
//./store文件 const store = new Vuex.Store({ state: { //放置state的值 count: 0, strLength:"abcd234" }, getters: { //放置getters方法 strLength: state => state.aString.length }, mutations: { //放置mutations方法 mutationName(state) { //在這裏改變state中的數據 state.count = 100; } }, // 異步的數據操做 actions: { //放置actions方法 actionName({ commit }) { //dosomething commit('mutationName') }, getSong ({commit}, id) { api.getMusicUrlResource(id).then(res => { let url = res.data.data[0].url; }) .catch((error) => { // 錯誤處理 console.log(error); }); } } }); export default store;
後續在組件中使用的過程當中,若是想要獲取對應的狀態你就能夠直接使用this.$store.state獲取,固然,也能夠利用vuex提供的mapState輔助函數將state映射到計算屬性中去,如
import {mapState} from 'vuex' export default { //組件中 computed: mapState({ count: state => state.count }) }
Getters
有些狀態須要作二次處理,就可使用getters。經過this.$store.getters.valueName對派生出來的狀態進行訪問。或者直接使用輔助函數mapGetters將其映射到本地計算屬性中去。
在組件中使用方式
import {mapGetters} from 'vuex' export default { computed: mapGetters([ 'strLength' ]) }
Mutations
Mutations的中文意思是「變化」,利用它能夠更改狀態,本質就是用來處理數據的函數,其接收惟一參數值state。store.commit(mutationName)是用來觸發一個mutation的方法。須要記住的是,定義的mutation必須是同步函數,不然devtool中的數據將可能出現問題,使狀態改變變得難以跟蹤。
在組件中觸發:
export default { methods: { handleClick() { this.$store.commit('mutationName') } } }
或者使用輔助函數mapMutations直接將觸發函數映射到methods上,這樣就能在元素事件綁定上直接使用了。如:
import {mapMutations} from 'vuex' export default { methods: mapMutations([ 'mutationName' ]) }
Actions
Actions也能夠用於改變狀態,不過是經過觸發mutation實現的,重要的是能夠包含異步操做。其輔助函數是mapActions與mapMutations相似,也是綁定在組件的methods上的。若是選擇直接觸發的話,使用this.$store.dispatch(actionName)方法。
在組件中使用
import {mapActions} from 'vuex' //我是一個組件 export default { methods: mapActions([ 'actionName', ]) }
Plugins
插件就是一個鉤子函數,在初始化store的時候引入便可。比較經常使用的是內置的logger插件,用於做爲調試使用。
//寫在./store文件中 import createLogger from 'vuex/dist/logger' const store = Vuex.Store({ ... plugins: [createLogger()] })