效果:
思路:
采用vue中 [computed:] 派生属性的方式实现联动效果,上边两个切换时,下边的跟随变动
demo代码:
<template><div><!-- 第一个下拉框 --><select v-model="firstValue"><option v-for="option in options" :key="option" :value="option">{{ option }}</option></select><!-- 第二个下拉框 --><select v-model="secondValue"><option v-for="option in options" :key="option" :value="option">{{ option }}</option></select><!-- 输入框,显示结果 --><input type="text" :value="computedValue" readonly /></div>
</template><script>
export default {data() {return {firstValue: null,secondValue: null,options: [10, 20, 30, 40, 50], // 假设下拉框选项为数字};},computed: {computedValue() {// 计算输入框中的值,避免出现 NaN 或空值if (this.firstValue !== null && this.secondValue !== null) {return this.firstValue - this.secondValue;}return ''; // 若下拉框未选择,则返回空字符串},},
};
</script>
结合实际应用还可以升级提炼
HTML代码:
<el-form ref="form" :model="form" :rules="rules" label-width="110px"><el-form-item label="第一个下拉框" prop="attributeId"><el-select v-model="form.attributeId" clearable filterable style="width:100%" :disabled="updateStatus == 1" placeholder="请选择"><el-optionv-for="item in bizAttributesList":key="item.id":label="item.attributeName":value="item.id"/></el-select></el-form-item> <el-form-item label="第二个下拉框" prop="relAttributeId"><el-select v-model="form.relAttributeId" clearable filterable style="width:100%" :disabled="updateStatus == 1" placeholder="请选择"><el-optionv-for="item in bizAttributesList":key="item.id":label="item.attributeName":value="item.id"/></el-select></el-form-item> <el-form-item label="输入框" prop="bizRelDesc"><el-input v-model="form.bizRelDesc" :value="computedValue" disabled/></el-form-item>
</el-form>
结合实际情况基本前两种,获取到的是id累的标志,所以需要在方法中过滤出显示的值
方法代码:
computed: {computedValue() {let attributeIdValue = ''let relAttributeIdValue = ''// 计算输入框中的值,避免出现 NaN 或空值if (this.form.attributeId && this.form.relAttributeId) {//两个都有值this.bizAttributesList.forEach(item=>{if(item.id === this.form.attributeId){attributeIdValue = item.attributeName}if(item.id === this.form.relAttributeId){relAttributeIdValue = item.attributeName}})return this.form.bizRelDesc = `${attributeIdValue}-${relAttributeIdValue}`}else if(this.form.attributeId && !this.form.relAttributeId){//第一个有值 第二个没有this.bizAttributesList.forEach(item=>{if(item.id === this.form.attributeId){attributeIdValue = item.attributeName}})return this.form.bizRelDesc = `${attributeIdValue}-`}else if(!this.form.attributeId && this.form.relAttributeId){//第二个有值 第一个没有this.bizAttributesList.forEach(item=>{if(item.id === this.form.relAttributeId){relAttributeIdValue = item.attributeName}})return this.form.bizRelDesc = `-${relAttributeIdValue}`}return ''; // 若下拉框未选择,则返回空字符串},},