我正在构建一个可用于设置各种 vuex 属性的组件,具体取决于路由中传递的名称。这是它的天真要点:
<template>
<div>
<input v-model="this[$route.params.name]"/>
</div>
</template>
<script>
export default {
computed: {
foo: {
get(){ return this.$store.state.foo; },
set(value){ this.$store.commit('updateValue', {name:'foo', value}); }
},
bar: {
get(){ return this.$store.state.bar; },
set(value){ this.$store.commit('updateValue', {name:'bar', value}); }
},
}
}
</script>
请注意,我将 this[$route.params.name]
传递给 v-model
,以使其动态化。这适用于设置(组件加载正常),但是当尝试设置一个值时,我收到此错误:
无法在未定义、null 或原始值上设置响应式属性:null
我假设这是因为 v-model
中的 this
变为未定义(?)
我怎样才能让它工作?
更新
我也很想知道为什么这不起作用(编译错误):
<template>
<div>
<input v-model="getComputed()"/>
</div>
</template>
<script>
export default {
computed: {
foo: {
get(){ return this.$store.state.foo; },
set(value){ this.$store.commit('updateValue', {name:'foo', value}); }
},
bar: {
get(){ return this.$store.state.bar; },
set(value){ this.$store.commit('updateValue', {name:'bar', value}); }
},
},
methods: {
getComputed(){
return this[this.$route.params.name]
}
}
}
</script>
最佳答案
是的,你的<template>
里面的一切在this
范围,所以 this
未定义。
v-model
只是 :value
的语法糖和 @input
,因此您可以使用自定义事件和 :value
的计算属性来处理此问题.
您还可以将计算属性与 getter 和 setter 一起使用;有点像
computed: {
model: {
get: function () {
return this.$store.state[this.$route.params.name]
},
set: function (value) {
this.$store.commit('updateValue', { name: this.$route.params.name, value})
}
}
}
编辑 如果您在 setter 中有更多逻辑要做,我会像这样将其分开,保持 getter 简单,并坚持使用一个计算属性;
computed: {
model: {
get: function () {
return this.$store.state[this.$route.params.name]
},
set: function (value) {
switch(this.$route.params.name) {
case 'foo':
return this.foo(value)
default:
return this.bar(value)
}
}
}
},
methods: {
foo(val) {
this.$store.commit(...)
},
bar(val) {
this.$store.commit(...)
}
}
关于javascript - 计算属性的动态 `v-model` - 基于路由参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54198300/