gpt4 book ai didi

javascript - Vue + vuex 对象突变

转载 作者:行者123 更新时间:2023-11-29 23:38:06 26 4
gpt4 key购买 nike

我有一个状态:

state: {
objects: [
{
id: 10,
key2: 'smth',
key3: 'smth'
//etc...
},
{
id: 12',
key2: 'smth',
key3: 'smth'
//etc...
}
]
}

我通过 id 选择一个,然后通过 v-model 更改它的 key 。

setter/getter

  activeObject: state => {
return state.objects.find((obj) => obj.id === state.objId)
}

在 vue 模板中

  computed: {
obj() {
return this.$store.getters.activeObject
}
},

在 html 中

<input v-model="obj.key2"></input>

问题是 vuex 告诉我必须只对突变进行更改。我看到了许多解决方案,例如 computed: get() set() 或 _.deepClone 或仅更改一个键。但是我可以做些什么来通过突变中的 id 重写整个对象?我在数组中的对象可能有很多键,所以将更新提交函数写入每个键会非常痛苦..

是否有一种解决方案可以通过 1 次提交重写具有多个键的对象?

请不要告诉我使用 lodash 或其他 lbis,只使用普通的 vue/js。

最佳答案

Is there a solution to rewrite object with many keys with 1 commit?

当然有:

myMutation(state, { id, newItem }) {
const item = state.objects.find(item => item.id === id);
Object.assign(item, newItem);
}

//...
const params = { id: 23, newItem: myNewItem };
store.commit('myMutation', params);

请注意,Vue 不会观察数组内部的变化。它不会对它们使用react。


OP添加源代码示例后编辑

您所做的是违反 Vuex 的“单向数据流”概念。 Vuex docs 中准确解释了如何处理您的用例:

Assuming obj is a computed property that returns an Object from the store, the v-model here will attempt to directly mutate obj.message when the user types in the input. In strict mode, this will result in an error because the mutation is not performed inside an explicit Vuex mutation handler. The "Vuex way" to deal with it is binding the 's value and call an action on the input or change event.

因此使用像这样的事件处理程序

updateObj (e) {
this.$store.commit('updateObj', e.target.value);
}

这是通过您的 HTML 代码调用的

<input :value="message" @input="updateObj">

请注意,如前所述,Vue 是否能够在存储的 Object 上看到您的更改s/Array s 取决于您如何定义它们以及如何访问它们,请参阅 Vuex mutations .

关于javascript - Vue + vuex 对象突变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45901200/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com