2017-11-25 169 views
0

邏輯我不知道如何組織我的Vuex商店給出以下問題。Vuex:觀察狀態

我有一個按鈕/操作數組,像100個。他們都在店裏像這樣的組織:

buttons: [ 
    { 
    text: 'Button 1', 
    doAction (store) {}, 
    mustShow (store) { 
     return state.variable > 10 && state.variable2.counter < 12 && !state.variable3 
    } 
    } 
    ... 
] 

我可以很容易地在我的視圖中顯示他們和他們的行動鏈接到點擊事件:

<button v-for"button in buttons" @click="button.doAction()"></button> 

的問題是,每個按鈕可以顯示或者不基於它只知道的任意複雜邏輯,正如您在mustShow函數中看到的那樣。每個按鈕都有其獨特的邏輯。

我可以很容易地僅返回其mustShow函數返回真有隻必須在店裏的特定狀態下顯示的動作按鈕的吸氣劑:

availableActions (state) { 
    return state.buttons.filter(s => s.mustShow()) 
} 

這工作的第一次,但問題是,當然這個getter沒有反應,因爲它沒有綁定到狀態變量,而是綁定到一個沒有反應的函數的結果。

你將如何組織代碼來完成這項工作?當然,人們可以將所有按鈕的顯示邏輯放入單個獲取器中。但是如果我希望按鈕的名稱也是動態的(作爲基於狀態中的任意變量計算其值的函數的結果)呢?

感謝

回答

1

我覺得你在這裏走錯了路:作爲一個經驗法則,你不應該有複雜的對象,就像函數定義,定義您的商店的狀態。考慮商店狀態的一種方式是,應該能夠用JSON進行編碼,將其提供給朋友,然後如果將其解析回來並在同一個程序中使用它,則應該得到相同的結果,顯然國家內部的一個功能不適合這個。

我的建議是做一些事情,如:

const state = { 
    buttons: [ 
    { 
    text: 'Button 1', 
    id: 1 
    }, 
    ... 
    ] 
} 
... 
const actions = { 
    doAction ({commit}, {btnId}) { 
    // now you perform the action you want to do 
    ... 
    // finally if you want to change the state of your store you 
    // should commit a mutation, *do not change the state here!* 
    // let the mutation do their job 
    // here you put all the things the mutation may need to perform 
    // the change of the state 
    const payload = { btnId } 
    commit(changeSomethingInState, { payload }) 
    } 
} 

const mutations = { 
    changeSomethingInState (state, { payload }) { 
    state.something = payload 
} 
... 

這是店裏的定義。現在在你看來,你喜歡:

<button v-for"button in buttons" @click="dispatch('doAction', { btnId: button.id })"/> 
+0

那麼,基本上doAction(和mustShow)應該是一個具有長開關的大規模動作呢? – pistacchio

+0

這實際上取決於你點擊每個按鈕時會做什麼,如果你認爲你需要一個巨大的開關,你可能會考慮將vuex代碼進一步分割爲應用程序每個部分的模塊。 或者你可以像'btnAtions [1] =()=> {/ *按鈕1邏輯* /}'等等對每個id – Batato

+0

看看這個[vuex模塊](https:// vuex .vuejs.org/en/modules.html),它可能真的幫助你。 – Batato