我正在关注有关vuex表单处理的官方vuex教程:https://vuex.vuejs.org/guide/forms.html。我基本上在底部复制并粘贴了他们建议的双向计算属性的实现,但仍然收到一个错误消息,提示它无法读取未定义的属性“名称”:
[Vue warn]: Error in render: "TypeError: Cannot read property 'name' of undefined"
found in
---> <CustomForm> at src/components/Form.vue
<Register> at src/views/Register.vue
<App> at src/App.vue
<Root>
Form.vue:
<custom-input title="Name" v-model="name" placeholder="Name" required />
computed: {
name: {
get () {
return this.$store.state.form.name
},
set (value) {
this.$store.commit('updateForm', ('name', value))
}
}
我尝试在get函数中的return语句之前console.log(this.$store.state.form.name)
,但没有任何显示
答案 0 :(得分:1)
如果您想要一个可以更新state.form
对象上任何值的突变,那么我会做类似的事情。
在突变中,使用键将值分配给正确的属性
mutations: {
updateForm (state, {key, value}) {
state.form[key] = value;
}
}
在提交中,使用一个对象作为具有键和值参数的有效负载
computed: {
name: {
get () {
return this.$store.state.form.name
},
set (value) {
this.$store.commit('updateForm', {key:'name', value});
}
}
答案 1 :(得分:0)
You can use mapFields to enable to way data binding
computed: {
...mapFields({
firstName: 'form.name',
lastName: 'form.lastName',
phoneNumber: 'form.phoneNumber',
emailAddress: 'form.emailAddress'
}),
},
将此添加到您的突变中 从“ vuex-map-fields”导入{updateField};
There is no need to add mutations to update the state this this done directly and using v-model you can bind these properties.