改变传入 payload 的 Vuex 数组
Mutate Vuex array passed in the payload
接下来的两种方法在技术上有什么区别?示例很简单,但是当我有巨大的嵌套对象时,我需要传递大量 ID 才能在突变中找到所需的对象。
在第二个示例中,我传递了一个数组并对其进行了修改。同样,从技术上讲,在两个示例中我们调用了相同的推送方法。我对吗?应该是一样的。
const state = () => ({
cards: []
});
mutations: {
addCard(state, card) {
state.cards.push(card)
}
}
// Component...
this.$store.commit('addCard', {...card});
和
const state = () => ({
cards: []
});
mutations: {
addCard(state, data) {
data.cards.push(data.card)
}
}
// Component...
this.$store.commit('addCard', { cards: this.$store.cards, card: {...card} });
What's the technical difference... ?
我知道你不是在问两者之间的字面区别是什么,但我先说清楚。
- 在第一个片段中,您传递了一个新项目并将其添加到您通过突变的
state
参数访问的数组状态。
- 在第二个代码段中,您同时传递数组状态和项目,而是通过有效负载访问数组。
Again, technically in both examples we invoke same push method. Am I right?
是的,这两个实现了完全相同的结果。数组状态,无论是通过突变参数还是通过有效负载访问,都是完全相同的对象(即 ===
)。
第二个片段中的模式在改变深层嵌套状态时非常有用,就像您发现的那样。缺点是对于稍后尝试学习您的代码的人来说,可能不太清楚发生了什么变化。
接下来的两种方法在技术上有什么区别?示例很简单,但是当我有巨大的嵌套对象时,我需要传递大量 ID 才能在突变中找到所需的对象。
在第二个示例中,我传递了一个数组并对其进行了修改。同样,从技术上讲,在两个示例中我们调用了相同的推送方法。我对吗?应该是一样的。
const state = () => ({
cards: []
});
mutations: {
addCard(state, card) {
state.cards.push(card)
}
}
// Component...
this.$store.commit('addCard', {...card});
和
const state = () => ({
cards: []
});
mutations: {
addCard(state, data) {
data.cards.push(data.card)
}
}
// Component...
this.$store.commit('addCard', { cards: this.$store.cards, card: {...card} });
What's the technical difference... ?
我知道你不是在问两者之间的字面区别是什么,但我先说清楚。
- 在第一个片段中,您传递了一个新项目并将其添加到您通过突变的
state
参数访问的数组状态。 - 在第二个代码段中,您同时传递数组状态和项目,而是通过有效负载访问数组。
Again, technically in both examples we invoke same push method. Am I right?
是的,这两个实现了完全相同的结果。数组状态,无论是通过突变参数还是通过有效负载访问,都是完全相同的对象(即 ===
)。
第二个片段中的模式在改变深层嵌套状态时非常有用,就像您发现的那样。缺点是对于稍后尝试学习您的代码的人来说,可能不太清楚发生了什么变化。