Vuex 的異步數據更新(小記)

更改 Vuex 的 store 中的狀態的惟一方法是提交 mutation。Vuex 中的 mutation 很是相似於事件:每一個 mutation 都有一個字符串的 事件類型 (type) 和 一個 回調函數 (handler)。這個回調函數就是咱們實際進行狀態更改的地方,而且它會接受 state 做爲第一個參數
mutation 是同步執行,不是異步執行。ios

因爲Mutations不接受異步函數,要經過Actions來實現異步請求。

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 的方法
    })
};

在Mutations中經過putSSS接收並更新style數據:

export const putSSS=(state, val) => {
    state.style = val;
};

組件建立時更新數據,寫在 created 中

this.$store.dispatch('setStyle',{
    id:this.id,
    name: this.name,
    });

使用 mapActions

使用 mapActions 輔助函數將組件的 methods 映射爲 store.dispatch 調用(須要先在根節點注入 store)json

methods: {
    ...mapActions([
        'setStyle'
    ]),
    test(){
    // 映射後可直接使用方法,不須要寫 this.$store.dispatch
     this.setStyle({
         id:this.id,
        name: this.name,
     });
    }
}
相關文章
相關標籤/搜索