vue- element三级联动:调接口做法

882 阅读2分钟

现在的一个项目是一个三级联动的下拉选择框。一二三级。

image.png

image.png

form表单:三个选择框

<el-form-item label="所属分类" prop="classList">
  <el-select 
  v-model="queryParams.oneClassificationId" 
  placeholder="一级分类"
  @change="changeOneClassification" clearable>
<el-option v-for="dict in classList" :key="dict.id" :label="dict.name" :value="dict.id" />
</el-select>
<el-select 
v-model="queryParams.twoClassificationId" 
placeholder="二级分类" 
@change="changeTwoClassification" clearable>
<el-option v-for="dict in twoClassList" :key="dict.id" :label="dict.name" :value="dict.id" />
</el-select>
<el-select 
v-model="queryParams.threeClassificationId" 
placeholder="三级分类" clearable>
<el-option v-for="dict in threeClassList" :key="dict.id" :label="dict.name" :value="dict.id" />
</el-select>
</el-form-item>

代码解析

 v-model="queryParams.oneClassificationId" 

是选择内容后,文本框里显示的值;

 @change="changeOneClassification"
 @change="changeTwoClassification" 

  • change当选中节点变化时触发,回调参数是选中节点的值。

关键:获取列表值

  • 一级选择框的内容在classList里面;
  • 二级选择框的内容在twoclassList里面;
  • 三级选择框的内容在threeclassList里面 所以要去接口里面获取这三个List的值

调用接口,获取三级选择器的内容

  • 接口说明:
    • 下拉一二三级分类, 如果选择一级分类传level = 1即可 ,
    • 如果选择二级分类传level = 2 和 parentId 等于 之前选择一级分类的id;
    • 如果选择三级分类传level = 3 和 parentId 等于之前选择二级分类的id 意思就是要想从接口里面获取内容,就要给接口传两个参数:
    • 参数1:level:分类等级:一级分类传1 , 二级分类传2 , 三级分类传3;
    • 参数2:parentId:选择的上一级id; image.png
    • 当调用这个_getLevel函数时,就会获取三级分类的值。
      • _getLevel函数,传一个值是data,是一个对象,里面有值 { level: 1 },
      • 所以默认data是{level:1}
    • 函数里面调用接口时给它传了一个参数data,这个data就是默认的情况下 { level: 1 },
      • 先设置好默认情况,在进行实际的数句判断:
      • 把data赋值给{level}对象;
        • 如果level==1,则获取第一级数据;
        • 如果level==2,则获取第二级数据;
        • 如果level==3,则获取第三级数据。
  • 从接口里面获取值,获取用到的值
// 查询三级选择列表
_getLevel(data = { level: 1 }) {
  getLevel(data).then(res => {
    const { level } = data
     if (level == 1) {
     this.classList = res.data
	} else if (level == 2) {
	this.twoClassList = res.data
	} else if (level == 3) {
      this.threeClassList = res.data
	}
	})
   },

方法中调用函数,如何处理

  • 当点击一级分分类按钮时,二级分类和三级分类列表都为空;
   methods: {
		changeOneClassification(e) {
			this.twoClassList = []
			this.threeClassList = []
			if (this.queryParams.twoClassificationId) {
				this.queryParams.twoClassificationId = ''
			}
			if (this.queryParams.threeClassificationId) {
				this.queryParams.threeClassificationId = ''
			}

			if (this.form.twoClassificationId) {
				this.form.twoClassificationId = ''
			}
			if (this.form.threeClassificationId) {
				this.form.threeClassificationId = ''
			}
			this._getLevel({
				level: 2,
				parentId: e,
			})
		},
		changeTwoClassification(e) {
			this.threeClassList = []
			// this.queryParams.threeClassificationName = ''
			if (this.queryParams.threeClassificationId) {
				this.queryParams.threeClassificationId = ''
			}
			if (this.form.threeClassificationId) {
				this.form.threeClassificationId = ''
			}
			this._getLevel({
				level: 3,
				parentId: e,
			})
		},