本次使用的Element版本为2.15.7,使用官方文档基础用法做示范。刚接触vue,如有不足,请指教

首先将代码copy下来,添加focus方法,删除data中的静态数据,最后在methods中实现focus方法
- Vue部分:
<el-select v-model="value" placeholder="请选择" @focus="getChoiceList">
<el-option
v-for="item in options"
:key="item.value"
:label="item.typeName"
:value="item.id"
>
</el-option>
</el-select>
这里插一句,其中item.typeName,item.id中的typeName和id一定要和后端中实体类的字段对应。

- JS部分:
<script>
export default {
data() {
return {
options: [],
value: "",
};
},
methods:{
getChoiceList(){
}
}
};
</script>
- 在
xxx.js文件(自己项目中的与后端对接的接口文件)中编写获取选择列表的API。以Vue-Element-Admin框架为例,就在vue-element-admin\src\api目录下
import http from '@/utils/request'
//获取支出类型
export async function getExChoiceListApi(parm){
return await http.get("/api/expense/exChoiceList",parm)
}
这个get请求方法是经过封装过的,封装代码如下:
const http = {
get(url, params) {
return service.get(url, {
params: params,
paramsSerializer: (params) => {
return qs.stringify(params)
}
})
}
}
- 对接后端,注意后端get请求的url一定要和前端请求的url保持一致
//支出类型列表
@GetMapping("/exChoiceList")
public ResultVo getChoiceList(){
List<Extype> chList = extypeService.list();
return ResultUtils.success("成功",chList);
}
- 引入请求方法
getExChoiceListApi方法并完成获取下拉菜单getChoiceList方法的书写
async getChoiceList(){
let res = await getExChoiceListApi(this.parms);
if (res && res.code == 200) {
console.log(res.data);
this.options = res.data;
}
}
完整的Vue代码如下:
<template>
<el-select v-model="value" placeholder="请选择" @focus="getChoiceList">
<el-option
v-for="item in options"
:key="item.value"
:label="item.typeName"
:value="item.id"
>
</el-option>
</el-select>
</template>
<script>
import { getExChoiceListApi } from "@/api/expense";
export default {
data() {
return {
options: [],
value: "",
};
},
methods:{
async getChoiceList(){
let res = await getExChoiceListApi(this.parms);
if (res && res.code == 200) {
console.log(res.data);
this.options = res.data;
}
}
}
};
</script>
最后效果:

本文介绍如何在Vue项目中使用Element UI的Select组件,通过前后端交互动态获取下拉选项列表。从配置Select组件到后端接口设计,再到前端获取数据的方法,一步步解析其实现过程。
1207

被折叠的 条评论
为什么被折叠?



