Element Select 选择器从后台获取并显示数据

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

在这里插入图片描述
首先将代码copy下来,添加focus方法,删除data中的静态数据,最后在methods中实现focus方法

  1. 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.typeNameitem.id中的typeNameid一定要和后端中实体类的字段对应。
在这里插入图片描述

  1. JS部分:
<script>
export default {
  data() {
    return {
      options: [],
      value: "",
    };
  },
  methods:{
    getChoiceList(){
      
    }
  }
};
</script>
  1. 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)
	      }
	   })
	}
} 
  1. 对接后端,注意后端get请求的url一定要和前端请求的url保持一致
	//支出类型列表
    @GetMapping("/exChoiceList")
    public ResultVo getChoiceList(){
        List<Extype> chList = extypeService.list();
        return ResultUtils.success("成功",chList);
    }
  1. 引入请求方法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>

最后效果:

在这里插入图片描述

  • 17
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Otto_1027

蟹蟹你,我会继续努力的~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值