Vue.js动态绑定 V 模型和值



I use django-rest-framework + vue.js

我的目标是制作一个表单来编辑用户配置文件。

这是我所拥有的:

<input type="email" v-model="userEdit.email">
<input type="text" v-model="userEdit.location">
<input type="text" v-model="userEdit.bio">

我的输入绑定到数据对象"编辑用户">

data() {
return {
'editUser': {
email: '',
location: '',
bio: '',
image: '',
},
}
},

所以现在我可以将此对象发送到服务器并更改用户配置文件信息。

sendChanges() {
const fd = new FormData();
fd.append('image', this.editUser.image, this.editUser.image.name)
fd.append('email', this.editUser.email)
fd.append('location', this.editUser.location)
fd.append('bio', this.editUser.bio)
this.axios.put(userDetailURL + this.routeUser, fd)
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error.response)
})
},

此表单有效并更新信息,但有一件事我不喜欢:

输入字段始终为空,用户需要填写所有字段,然后才能按保存按钮。

即使用户只想更改"位置",他也必须填写其他空输入。

向输入添加动态:value="userDetail.email"- 没有工作。

有没有其他方法可以将当前值添加到输入字段并且仍然具有 V 模型? 当前数据在这里:

computed: {
userDetail() {
return this.$store.getters.userDetail;
},
},

问题是您将data中的值绑定到表单,而这些值最初为空。

我现在能想到的最干净、最简单的解决方案是更新生命周期钩子mounted初始数据:

mounted () {
// Use Object.clone to prevent modifying the userDetail object directly
this.editUser = Object.clone(this.$store.getters.userDetail)
}

不过,还有其他解决方案。您可以使用计算资源库,其 getter 默认为存储中的任何内容,但在设置时可以覆盖。

最新更新