Bootstrap Vue框架下输入框联动自动填充其他表单字段实现咨询
完整实现代码
<template> <div class="m-2 mt-3"> <table class="table table-striped mt-2"> <tbody> <h5 class="ml-1">Informations</h5> <tr> <div class="row"> <div class="col-md-6 m-1"> <div class="mt-2">number1</div> <b-form-input class="form-control" placeholder="1234567" id="number1" v-model="numberInput" @input="handleAutoFill" /> </div> </div> <div class="row"> <div class="col-md-5 ml-1 mr-1"> <div class="mt-2">autofill1</div> <b-form-select id="autofill1" v-model="selectedFill1" :options="fill1Options" > </b-form-select> </div> <div class="col-md-5 ml-1 mr-1"> <div class="mt-2">autofill2</div> <b-form-select id="autofill2" v-model="selectedFill2" :options="fill2Options" > </b-form-select> </div> <div class="row"> <div class="col-md-3 mt-2 ml-1"> <b-button variant="success" type="submit"><b-icon icon="check-circle-fill"></b-icon> Save Changes</b-button> </div> </div> </div> </tr> </tbody> </table> </div> </template> <script> export default { data() { return { // 绑定number1输入框的值 numberInput: '', // 绑定两个下拉框的选中值 selectedFill1: '', selectedFill2: '', // 导入你的JSON数据源 dataSource: [ { "number": 1234567, "autofill1": "Hello", "autofill2": "Goodbye" }, { "number": 9876543, "autofill1": "Ciao", "autofill2": "Arrivederci" }, { "number": 1346795, "autofill1": "Hallo", "autofill2": "Tschuess" } ], // 下拉框可选值,自动从数据源去重生成,也可以手动自定义 fill1Options: [], fill2Options: [] } }, created() { // 初始化下拉框选项 this.fill1Options = [...new Set(this.dataSource.map(item => item.autofill1))] this.fill2Options = [...new Set(this.dataSource.map(item => item.autofill2))] }, methods: { handleAutoFill() { // 清空输入时自动清空两个下拉框 if (!this.numberInput) { this.selectedFill1 = '' this.selectedFill2 = '' return } // 匹配数据源,转成字符串对比兼容数字和文本格式输入 const matchItem = this.dataSource.find(item => String(item.number) === String(this.numberInput)) if (matchItem) { this.selectedFill1 = matchItem.autofill1 this.selectedFill2 = matchItem.autofill2 } else { // 没有匹配到的时候可以清空或者保留原值,根据需求调整 this.selectedFill1 = '' this.selectedFill2 = '' } } } }; </script> <style scoped> </style>
可调整规则说明
- 如果两个下拉框不需要用户手动选择,仅用于展示自动填充的值,可以把
b-form-select换成b-form-input加readonly属性即可 - 匹配规则可按需修改,比如需要模糊匹配的话,把
find里的全等判断换成includes即可 - 如果数据源是后端接口返回的,把
dataSource的赋值替换成接口请求逻辑即可
内容的提问来源于stack exchange,提问作者patrick96
相关产品推荐
相关产品推荐

