使用Vuex的步驟:
(1)安裝:
1.使用npm安裝:
npm install vuex --save
2.使用script標簽引入
<script src="/path/to/vue.js"></script> <script src="/path/to/vuex.js"></script>
如果使用第一種方式安裝Vuex插件,在使用Vuex插件之前需要在main.js入口文件中
1‘ 使用import方式引入Vuex
import Vuex from ‘vuex’
2‘ 使用Vue的插件引入函數Vue.use()使用Vuex
Vue.use(Vuex);
(2)安裝之后可以通過Vuex實例對象的Store方法創建一個store對象:
var store = new Vuex.Store({ state:{ NewMsg:{ Msgs:[ { title:'暫無消息', content:'暫無消息!', url:'#no_msg', id:'no_msg' } ] }, }, mutations:{ modifyMsg (state,Obj){ if(state.NewMsg.Msgs[0].id === 'no_msg'){ state.NewMsg.Msgs.shift(); } var obj = { title:Obj.title, content:Obj.content }; obj.id = 'Msg_' + Obj.id; obj.url = '#' + obj.id; state.NewMsg.Msgs.push(obj); } }, actions:{ fetchMsg (context){ $.ajax({ url:'PHP/GetMsgs.php', type:'GET', data:{}, dataType:'json', success:function(response){ if ( typeof response === 'string') { response = JSON.parse(response); } console.log(response); $(response).each(function(k,v){ // console.log(v.id+v.title+v.content); context.commit('modifyMsg',v); }); } }); } } });
(3)在Vue實例中注冊store對象:
new Vue({ el: '#app', router, store, created (){ store.dispatch('fetchMsg'); }, template: '<App/>', components: { App } })
(4)在組件中使用state數據:
必須通過computed屬性使用state數據!否則state屬性中的數據發生更改時不會反映在組件上!
export default { computed: { Msgs (){ var Msgs = this.$store.state.NewMsg.Msgs; return Msgs; } } }
注意事項:
基本組成:
注意到這個store對象包含三個子對象:
state、mutations、actions
其中state用於存儲數據,類似vue實例的data屬性。
mutations用於遞交更改,對state對象中的屬性數據進行更改。
actions用於進行遞交異步更改,通過調用mutations實現對數據的更改。
actions與mutations的區別:
其中actions區別於mutations的地方在於mutations只能進行同步更改,而actions中的更改可以是異步執行。所以基本上所有用戶執行的直接數據更改都是觸發mutations屬性
函數執行,而需要與后端進行數據交互的數據更改通常是通過actions屬性函數去執行。
定義actions與mutations屬性函數的注意事項:
其中定義mutations屬性函數時必須傳遞的第一個參數是state,因為要對state進行更改,第二個參數代表傳入的新參數。mutations屬性函數只接受兩個參數,如果要同時更
改多個屬性值,可以通過對象傳入。
在actions屬性函數中可以通過context.commit()方法觸發mutations屬性函數。定義actions屬性函數時,必須傳遞的第一個參數是context,用於觸發mutations函數。
觸發actions與mutations屬性函數的方法:
在子組件中通過this.$store.commit()方法觸發mutations屬性函數。在注冊store的Vue實例中(第三步中將會講到)可以通過store.commit()觸發。
commit函數第一個參數是mutations的屬性函數名,第二個參數是傳入的新值。
actions屬性函數中可以進行異步操作,比如通過ajax或者Vue.Resource()進行數據獲取,獲取數據后再通過context.commit()觸發更改。
觸發actions屬性函數使用this.$store.dispatch()或者store.dispatch() (在注冊store的Vue實例中)函數。dispatch函數傳遞的一個參數是actions屬性函數名稱。如果希望在
Vue實例創建完成還未掛載時就從后端獲取數據,則可以在created鈎子函數中調用actions屬性函數。
在組件中訪問數據中心state的注意事項:
在Vue實例中可以通過this.$store.state對象獲取state中的數據。如果希望在state中的數據發生更改之后,組件會自動更新,則應該使用組件的computed屬性定義數據,而
不是通過data屬性定義。如果使用data定義組件數據,則state中的數據發生更改之后組件不會發生變化。
export default { computed: { Msgs (){ var Msgs = this.$store.state.NewMsg.Msgs; return Msgs; } } }