ElementUI中el-sellect请求springboot后台数据显示下拉项并在el-table中格式化显示

场景

Vue+ElementUI+axios+SpringBoot前后端分离的后台管理系统。

将表格中某字段类似于状态等需要关联字典表进行筛选查询时。示例如下

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

首先实现前端页面下拉框赋值

在页面上添加一个el-table

          <el-form-item label="调动类别" prop="ddlb">
            <el-select v-model="queryParams.ddlb" placeholder="请选择调动类别" clearable size="small">
              <el-option
                v-for="dict in ddlbOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>

这里绑定的下拉框的数据源是一个ddlbOption这个对象数组,这是一个请求后台数据返回的键值对的数组。

首先需要声明这个对象数组

  data() {
    return {
      // 调动类别字典
      ddlbOptions: [],

然后在页面的created函数中请求后台获取字典数据,这样在页面加载完就能获取数据。

  created() {
    this.getDicts("kq_ddlx").then((response) => {
  },

调用的方法getDicts是外部引用的公共方法,能根据字典类型获取字典数据

// 根据字典类型查询字典数据信息
export function getDicts(dictType) {
  return request({
    url: '/system/dict/data/type/' + dictType,
    method: 'get'
  })

请求的后台url对应的接口中

    /**
     * 根据字典类型查询字典数据信息
     */
    @GetMapping(value = "/type/{dictType}")
    public AjaxResult dictType(@PathVariable String dictType)
    {
        return AjaxResult.success(dictTypeService.selectDictDataByType(dictType));
    }

在Controller层调用servive

public List<SysDictData> selectDictDataByType(String dictType);

在ServiceImpl

   public List<SysDictData> selectDictDataByType(String dictType)
    {
        List<SysDictData> dictDatas = DictUtils.getDictCache(dictType);
        if (StringUtils.isNotNull(dictDatas))
        {
            return dictDatas;
        }
        dictDatas = dictDataMapper.selectDictDataByType(dictType);
        if (StringUtils.isNotNull(dictDatas))
        {
            DictUtils.setDictCache(dictType, dictDatas);
            return dictDatas;
        }
        return null;
    }

到mapper层

public List<SysDictData> selectDictDataByType(String dictType);

对应的xml

 <select id="selectDictDataByType" parameterType="SysDictData" resultMap="SysDictDataResult">
  <include refid="selectDictDataVo"/>
  where status = '0' and dict_type = #{dictType} order by dict_sort asc
 </select>

就是对数据库中的字典表根据type类型进行查询

设计数据库如下

其中dict_lable作为值,dict_value作为键,dict_type相同作为一组,是类型的标志字段。

请求完字典数据并通过

              <el-option
                v-for="dict in ddlbOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />

给下拉框进行赋值后,下面就是对查询数据的格式化显示。

使用字典的目的就是在数据中存储的是键即1,2,3这种数据,而在页面上显示的是要对应的值即中文名 除了可以在后台进行查询时关联字典表进行查询,直接将查询结果返回给前端后。

还可以直接查询的就是表中存储的1,2,3这种数据,然后返回给前端,由前端进行格式化显示。

来到对应的状态列

<el-table-column label= "调动类别" align= "center" prop= "ddlb" :formatter= "ddlbFormat" />

添加格式化属性和方法,在格式化方法中

    // 调动类别字典翻译
    ddlbFormat(row, column) {
      return this.selectDictLabel(this.ddlbOptions, row.ddlb);
    },

传递的row是当前行对象,column是当前列对象

 return返回的就是当前列要显示的值,这里调用的是一个方法,传递的是上面获取的字典的数组和当前列的属性值即1,2,3这种。

调用的回显字典数据的方法

// 回显数据字典
export function selectDictLabel(datas, value) {
 var actions = [];
 Object.keys(datas).map((key) => {
  if (datas[key].dictValue == ('' + value)) {
   actions.push(datas[key].dictLabel);
   return false;
  }
 })
 return actions.join('');
}

能将上面查询的字典的数组根据键1,2,3回显值即中文名称。

这样在下拉框选择之后可以通过

<el-select v-model= "queryParams.ddlb"

绑定的值传递给后台,此时后台获取的是设置的value值即1,2,3等。

其中quarmParams是前端声明的对象,字段与后台的实体类的属性项相对应

      queryParams: {
        pageNum: 1,
        pageSize: 10,
        gh: undefined,
        xm: undefined,
        ddlb: undefined,
        ddsj: undefined,
        kssj: undefined,
        jssj: undefined,
        sfclwc: undefined,
        bmids: undefined,
      },

查询按钮时调用后台接口

    /** 查询调动记录列表 */
    getList() {
      listDdjl(this.queryParams).then((response) => {
        this.ddjlList = response.rows;
      });
    },

此时传递的参数就是

this.queryParams

这个就是上面前端声明的对象,其属性ddlb已经根据el-table的那列进行绑定

<el-select v-model= "queryParams.ddlb"

通过listDdjl请求后台

export function listDdjl(query) {
  return request({
    url: '/kqgl/ddjl/getListBySx',
    method: 'post',
    data: query
  })

}

其中request是封装axios的请求对象

import axios from 'axios'
import { Notification, MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'< /A>

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项,表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 10000
})
// request拦截器
service.interceptors.request.use(config => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  if (getToken() && !isToken) {
    config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  return config
}, error => {
    console.log(error)
    Promise.reject(error)< BR> })

// 响应拦截器
service.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
    const message = errorCode[code] || res.data.msg || errorCode['default']
    if (code === 401) {
      MessageBox.confirm(
        '登录状态已过期,您可以继续留在该页面,或者重新登录',
        '系统提示',
        {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        store.dispatch('LogOut').then(() => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
        })
      })
    } else if (code === 500) {
      Message({
        message: message,
        type: 'error'
      })
      return Promise.reject(new Error(message))
    } else if (code !== 200) {
      Notification.error({
        title: message
      })
      return Promise.reject('error')
    } else {
      return res.data
    }
  },
  error => {
    console.log('err' + error)
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }< BR> )

export default service

传递到后台接口

    @GetMapping("/list")
    public TableDataInfo list(KqDdjl kqDdjl)
    {
        startPage();
        List<KqDdjl> list = kqDdjlService.selectKqDdjlList(kqDdjl);
        return getDataTable(list);
    }

此时的实体类KqDdjl 的属性要与前端传递的参数的属性相对应,这样后台就能获取到。

public class KqDdjl extends BaseEntity
{
    private static final long serialVersionUID = 1L;

    /** id */
    private Long id;

    /** 调动类别 */
    @Excel(name = "调动类别")
    private String ddlb;

}

省略其他属性和get和set方法。

Controller层传递一直到mapper层

public List<KqDdjl> selectKqDdjlList(KqDdjl kqDdjl);

对应的xml方法

    <select id="selectKqDdjlList" parameterType="KqDdjl" resultMap="KqDdjlResult">
        <include refid="selectKqDdjlVo"/>
        <where>  
            <if test="ddlb != null  and ddlb != ''"> and ddlb = #{ddlb}</if>
        </where>
    </select>

省略其他属性字段和映射等。

这样就可以实现根据筛选的条件查询出符合条件的数据。

原文地址:https://www.cnblogs.com/badaoliumangqizhi/p/13447895.html