Laravel8+Vue3项目使用datalist选择学员后自动填充表单字段问题咨询
解决方案
1. 先修改组件data配置
新增搜索框绑定变量、表单统一绑定对象,避免零散ref操作:
data() { return { trainees: [], searchInput: '', // 绑定datalist搜索输入框 // 表单统一绑定对象,字段名和你后端返回的学员字段对齐即可 form: { lastname: '', firstname: '', email: '', company: '', vehicle: '', location: '', instructor_id: '', acp_center_id: '' }, // 你原有代码用到的其他变量保留即可 instructors: [], acpCenters: [] } }
2. 修改datalist部分代码
给输入框加双向绑定和选择触发事件,给option显式设置value属性避免浏览器兼容问题:
<div class="search_trainee"> <input id="search" class="search_trainee_input" list="trainees" placeholder=" " type="text" v-model="searchInput" @input="handleTraineeSelect"> <label class="label_search" for="search">Search a trainee</label> <datalist id="trainees"> <option v-for="user in trainees" :key="user.id" :value="`${user.firstname} ${user.lastname}`"> {{ user.firstname }} {{ user.lastname }} </option> </datalist> </div>
3. 新增学员选择匹配方法
datalist输入框只能拿到字符串,通过输入的姓名匹配数组里的完整学员对象,匹配成功后自动填充表单:
methods: { // 原有getTrainee方法保留 getTrainee() { axios.get(AXIOS + 'trainee') .then(response => this.trainees = response.data) .catch(error => console.log(error)); }, // 新增匹配填充方法 handleTraineeSelect() { const matched = this.trainees.find(item => `${item.firstname} ${item.lastname}` === this.searchInput) if (!matched) return // 填充表单字段 this.form.lastname = matched.lastname this.form.firstname = matched.firstname this.form.email = matched.email this.form.company = matched.company this.form.vehicle = matched.vehicle this.form.location = matched.location // 下拉框特殊处理,和你原有绑定格式保持一致 this.form.instructor_id = matched.instructor_id ? {id: matched.instructor_id} : '' this.form.acp_center_id = matched.acp_center_id ? {id: matched.acp_center_id} : '' }, // 其他原有方法保留 }
4. 修改表单部分的绑定
把所有表单输入框、下拉框的v-model绑定到form对应的字段即可,比如:
<!-- 举个例子,其他字段同理修改 --> <input id="lastname" class="form-control" name="lastname" placeholder=" " type="text" v-model="form.lastname" @blur.prevent="addTrainee();displayAudit()"> <select id="instructor_id" v-model="form.instructor_id" class="form-control" name="instructor_id" @blur.prevent="update"> <!-- 原有option不变 --> </select>
原有问题原因说明
- 出现
[object Object]是因为你之前直接把对象赋值给了只能识别字符串的输入框,触发了默认的toString转换 - 只能拿到字符串是datalist原生输入框的特性,本身只支持字符串值,所以需要通过匹配数组拿到完整学员对象
内容的提问来源于stack exchange,提问作者Bastien
相关产品推荐
相关产品推荐

