Vue中v-for内使用v-model绑定输入框所有输入同步填充如何解决
Vue多待办清单输入框内容同步问题解决方案
问题说明
存在多个待办清单(Todolist),在任意一个待办清单的输入框中输入内容时,其余所有待办清单的输入框都会同步填入相同内容。新待办提交功能本身正常,提交后会正确展示在对应所属的待办清单中,问题仅出现在输入环节的内容同步上。
问题根源
所有循环生成的输入框都绑定了同一个全局data属性todo.title,只要任意一个输入框修改了该属性值,所有绑定该属性的输入框都会同步更新显示内容。
原始错误实现代码
模板代码
<div class="todolist" v-for="todolist in todolists" :key="todolist.id"> <div class="td-title"> <h5 class="text-center m-0 py-2 text-light"> {{ todolist.title }} </h5> </div> <form @submit.prevent="addTodo(todolist.id)" class="td-inputs d-flex align-items-center justify-content-center" > <!-- 所有输入框都绑定了同一个todo.title --> <input v-model="todo.title" class="px-2" type="text" /> <button type="submit"> <i class="fas fa-plus fa-2x"></i> </button> </form> <div> <div v-for="todo in todolist.todos" :key="todo.id" class="todo"> {{ todo.title }} </div> <div> <i class="fas fa-times" @click="cancel(todolist.id)"></i> </div> </div> </div>
data定义
data() { return { todolists: [], loading: true, todo: { title: "", todolist_id: "", user_id: "" }, }; },
方法实现
getTodoLists() { axios .get("http://127.0.0.1:8000/api/todolists") .then((res) => { this.todolists = res.data; this.loading = false; }) .catch((err) => { console.log(err); }); }, cancel(id) { axios .delete(`http://127.0.0.1:8000/api/todolists/${id}`) .then(() => { this.getTodoLists(); }) .catch((err) => { console.log(err); }); }, addTodo(todolist) { axios .post(`http://127.0.0.1:8000/api/${todolist}/todos`, this.todo) .then(() => { this.todo = {} this.getTodoLists(); }) .catch((err) => { console.log(err); }); },
修复方案
通过带getter和setter的计算属性解除输入框和全局todo.title的双向绑定联动,修改后仅正在输入的输入框会显示内容,待办提交逻辑不受影响。
新增计算属性代码
computed: { getTitle: { get: function () { return ""; }, set: function (value) { this.todo.title = value; }, }, },
修改后的输入框绑定代码
<form @submit.prevent="addTodo(todolist.id)" class="td-inputs d-flex align-items-center justify-content-center" > <!-- 将绑定值替换为计算属性 --> <input v-model="getTitle" class="px-2" type="text" /> <button type="submit"> <i class="fas fa-plus fa-2x"></i> </button> </form>
实现原理
- 计算属性的getter固定返回空字符串,因此所有输入框不会读取全局
todo.title的内容,避免了多输入框内容同步 - 计算属性的setter会将输入的内容实时赋值给
todo.title,原有提交逻辑不需要做任何修改即可正常使用
内容的提问来源于stack exchange,提问作者D.D.
相关产品推荐
相关产品推荐

