javascript - Vuex v-model 到对象状态字段
问题描述
我有一个 Vuex 状态,像这样(它也有一个 getter,名为configs
:
configs: {
1303401: {
exampleValue: 'test'
}
}
我还有一个输入,我在其中exampleValue
对 Vuex 商店的状态进行 v 建模:
<input type="text" v-model="config.exampleValue" />
这是我用来返回的计算属性config
:
config: {
get () {
return this.$store.getters.configs[1303401]
},
set (value) {
//this should set the configs[1303401] field with the updated exampleValue
this.$store.dispatch('UPDATE_CONFIG', value)
}
}
输入的值变为 的值config.exampleValue
,因此计算的数据不是未定义的,但 Vuex 状态不会更新。
此外,如果我尝试console.log
设置设置器中的值,控制台中不会出现任何内容,因此设置器甚至不会执行
这可能是因为它没有设置config
计算属性,config.exampleValue
但是我不知道如何处理它。
正如上面提到的@asi-ple,将get更改为returnconfigs[1303401].exampleValue
会起作用,但问题是,配置有更多字段,页面有更多输入,我需要以这种方式为所有字段创建一个计算属性.
解决方案
实际上,如果你有多个字段,你可以在这里做一些逻辑。
可以说你有
configs: {
1303401: {
exampleValue: 'test',
exampleValue2: 'test2',
exampleValue3: 'test3',
...
}
}
比您应该将模板更改为:
<input type="text" :value="config[1303401].exampleValue1" @input="update_config($event, 'exampleValue1')" />
<input type="text" :value="config[1303401].exampleValue2" @input="update_config($event, 'exampleValue2')" />
<input type="text" :value="config[1303401].exampleValue3" @input="update_config($event, 'exampleValue3')" />
而你的方法是这样的
methods:{
update_config($event, where){
this.$store.commit("UPDATE_CONFIG", {value: $event.target.data, where: where})
}
}
然后你的突变处理程序看起来像这个
UPDATE_CONFIG(state, payload){
state.configs[1303401][payload.where] = payload.value
}
基本上上面的代码,你在你的状态下制作一个配置数据,它应该在你的模板中使用双向数据绑定。然后你正在创建你的输入 :value 像 get 方法一样工作,@input 监听器像 set 方法一样工作,然后 update_config 正在提交你的更改和突变处理程序将它们设置在正确的位置
推荐阅读
- php - php中有readdirectory函数吗
- scala - 对 Play for Scala 中的“内存不足错误:元空间”进行故障排除
- python - 熊猫:删除列表中名称并分配给新数据框的多个列
- html - HTML 页面 - 扩展数据
- php - 在 Woocommerce 中复制挂钩函数时避免错误 500
- html - SVG 图像 - 固定高度 - 保持比例 - 切片
- c# - NServiceBus XML 反序列化抛出:多个根元素
- react-native - React Native:列表的条件道具
- python - 确定哪些向量组合将与另一个向量相加
- node.js - 节点上的fabric.js - 旋转(setAngle)改变对象的位置