鉴于以下问题,我不知道如何组织我的 Vuex 商店。
我有一系列按钮/操作,大约有 100 个。它们在商店中的组织方式如下:
buttons: [
{
text: 'Button 1',
doAction (store) {},
mustShow (store) {
return state.variable > 10 && state.variable2.counter < 12 && !state.variable3
}
}
...
]
我可以轻松地在我的 View 中显示它们并将它们的操作链接到点击事件:
<button v-for"button in buttons" @click="button.doAction()"></button>
问题是每个按钮是否显示都可以基于它只知道的任意复杂逻辑,正如您在 mustShow
函数中看到的那样。每个按钮都有其独特的逻辑。
我可以轻松地创建一个 getter,仅返回 mustShow
函数返回 true 的按钮,以仅包含必须在商店的特定状态下显示的操作:
availableActions (state) {
return state.buttons.filter(s => s.mustShow())
}
这是第一次工作,但问题是,这个 getter 当然不是响应式的,因为它没有绑定(bind)到状态变量,而是绑定(bind)到非响应式函数的结果。
您将如何组织代码来完成这项工作?当然,可以将所有按钮的所有显示逻辑放入一个 getter 中。但是,如果我希望按钮的名称也是动态的(作为根据状态中的任意变量计算其值的函数的结果)怎么办?
谢谢
最佳答案
我认为你在这里走错了路:作为经验法则,你不应该有复杂的对象,比如函数定义,定义你的商店状态。考虑存储状态的一种方式是,您应该能够用 JSON 进行编码,将其提供给 friend ,然后您的 friend 如果解析它并在同一个程序中使用它,应该会得到相同的结果,很明显,状态内部的函数不适合这个。
我的建议是做类似的事情:
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 })"/>
关于javascript - Vuex:观察状态中的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47484722/