2017-11-11 73 views
1

的状态突变Vuex方法是如下:vuex如何改变store中的多个属性,如在redux中?

const store = new Vuex.Store({ 
    state: { 
    fetching: false, 
    board: null 
    }, 
    mutations: { 
    setFething (state) { 
     state.fetching = true 
    }, 
    setCurrentBoard (state, board) { 
     state.board = board 
     state.fetching = false 
    } 
    } 
}) 

但我担心它会引发两个转变为boardfetching每个属性独立而不是一个,我的观点将被更新双重倍。这只是一个简单的例子,我有更复杂的属性突变,会更好地突变一个突变。 vuex有可能吗?

我喜欢Redux的方法返回突变只有一次状态对象:

initialState = { board: null, fetching: false }; 
export default function reducer(state = initialState, action = {}) { 
    switch (action.type) { 
    case Constants.SET_FETCHING: 
     return { ...state, fetching: true }; 

    case Constants.SET_CURRENT_BOARD: 
     return { ...state, ...action.board, fetching: false }; 
} 
+0

使用Vuex acrions。创建您同时执行多项更改的操作。 – WaldemarIce

+0

这种情况是我不能一次返回新的不可变状态对象,但我必须分别改变每个属性。 – luzny

回答

2

那么,你在寻找这样的事情?

var store = new Vuex.Store({ 
 
    state: { 
 
    id: 1, 
 
    name: 'aaa', 
 
    last: 'bbb' 
 
    }, 
 
    mutations: { 
 
    change (state, payload) { 
 
     state = Object.assign(state, payload) 
 
    } 
 
    } 
 
}) 
 

 
new Vue({ 
 
    el: '#app', 
 
    store, 
 
    created() { 
 
    setTimeout(_ => { 
 
     this.$store.commit('change', { 
 
     id: 2, 
 
     last: 'ccc' 
 
     }) 
 
    }, 2000) 
 
    setTimeout(_ => { 
 
     this.$store.commit('change', { 
 
     name: 'ddd' 
 
     }) 
 
    }, 4000) 
 
    } 
 
})
<div id="app"> 
 
    {{ $store.state.id }} 
 
    <br> 
 
    {{ $store.state.name }} 
 
    <br> 
 
    {{ $store.state.last }} 
 
</div> 
 

 
<script src="https://unpkg.com/vue"></script> 
 
<script src="https://unpkg.com/vuex"></script>

相关问题