【vue 项目】element-select选择器 以省市下拉框联动为例 通过value获取label的值 将value和label都传给后端

element里面select组件v-model显示的是value的值,在实际的开发中经常需要同时向后端传递value和label的值
在这里插入图片描述

html

<el-form-item label="所属城市:" prop="city">
    <el-select v-model="addProductForm.city.city1" placeholder="请选择省份" size="small" style="width:220px;margin-right: 20px;" @change="selectCity">
       <el-option v-for="item in province" :key="item.id" :value="item.id" :label="item.name" />
    </el-select>
    <el-select v-model="addProductForm.city.city2" placeholder="请选择城市" size="small" style="width:220px;">
       <el-option v-for="item in cities" :key="item.id" :value="item.id" :label="item.name" />
   	</el-select>
</el-form-item>

在这里插入图片描述

JS

data中声明

addProductForm: {
    
    
	city: {
    
    
	  city1: '',
	  city2: ''
	}, // 所属城市
},

methods

methods: {
    
    
	// 查询省/直辖市
	async findprovince() {
    
    
	  const option = {
    
    
	    // ...接口请求参数
	  }
	  const res = await findCities(option)
	  if (res.code === 200) {
    
    
	    this.province = res.data
	  }
	},
	// 监听省 选择城市
	async selectCity(e) {
    
    
	  this.cities = [] 
	  this.addProductForm.city.city2 = '' // 每次选择完省 将市置空
	  const option = {
    
    
	    // ...接口请求参数
	    // 选择城市一般还有把选择的省id(e)传给后端
	  }
	  const res = await findCities(option)
	  if (res.code === 200) {
    
    
	    this.cities = res.data
	  }
	},
	confirm() {
    
    
		// 获取省市名称
		// element-select选择器 通过value获取label的值 将value和label都传给后端
		let cityName1 = {
    
    }
		cityName1 = this.province.find((item) => item.id === this.addProductForm.city.city1)
		this.addProductForm.provinceName = cityName1.name
		let cityName2 = {
    
    }
		cityName2 = this.cities.find((item) => item.id === this.addProductForm.city.city2)
		this.addProductForm.cityName = cityName2.name

		const option = {
    
    
			provinceId: this.addProductForm.city.city1,
			provinceName: this.addProductForm.provinceName,
			cityId: this.addProductForm.city.city2,
			cityName: this.addProductForm.cityName
		}
	}
 }

猜你喜欢

转载自blog.csdn.net/Aohanzzz/article/details/126738217