更改 Vuex 的 store 中的狀態的惟一方法是提交 mutation。Vuex 中的 mutation 很是相似於事件:每一個 mutation 都有一個字符串的 事件類型 (type) 和 一個 回調函數 (handler)。這個回調函數就是咱們實際進行狀態更改的地方,而且它會接受 state 做爲第一個參數
mutation 是同步執行,不是異步執行。ios
export const setAddPurchaseStyle = ({commit, state}, obj) => { url='http://xxx.com' + '/json/' + '/development' + '/purchaserexp/create_company.js'; let _tempObj={}; // 着鍵是這個 return return new Promise(function(resolve, reject) { axios.get(url, {}).then((response) => { resolve('請求成功後,傳遞到 then'); }, (response) => { //失敗 console.info('error', response); reject('請求失敗後,傳遞到 catch') }); }).then((res)=>{ // res 是 (請求成功後,傳遞到 then) commit('putSSS', Math.random()); // 在Promise的成功中,調用 mutations 的方法 }) };
export const putSSS=(state, val) => { state.style = val; };
this.$store.dispatch('setStyle',{ id:this.id, name: this.name, });
使用 mapActions 輔助函數將組件的 methods 映射爲 store.dispatch 調用(須要先在根節點注入 store)json
methods: { ...mapActions([ 'setStyle' ]), test(){ // 映射後可直接使用方法,不須要寫 this.$store.dispatch this.setStyle({ id:this.id, name: this.name, }); } }