Element表格和表单字典转换(静态和动态)(上)

简介: Element表格和表单字典转换(静态和动态)(上)

Element表格和表单字典转换(静态和动态)

使用vue、element对form和table做字典映射。非常简单方便。还附带了和springboot集成的接口动态方式

一、定义静态字典

1. 新建字典文件

首先在util文件夹新建一个dict.js

const dictList={
  statusList: [
    {id:0,name:'未使用'},
    {id:1,name:'已绑定'},
    {id:2,name:'已使用'},
    {id:3,name:'禁用'},
    {id:4,name:'作废'},
  ],
   boolList: [
    {id:0,name:'禁用'},
    {id:1,name:'启用'}
  ]
}
export default dictList

2. 新建字典工具类

在util文件夹新建getDict.js文件

import dictList from '@/utils/dict'
/**获取静态字典值 **/
export function getDict(data, element, dictName) {
  const col = element.property
  const dictArr = dictList[dictName]
  if (!dictArr) return
  for (let item of dictArr) {
    if (item.id === data[col]) {
      return item.name
    }
  }
}
/**获取静态字典列表 **/
export function getDictList (dictName) {
  return  dictList[dictName]
}

3. 挂载到Vue上

找到项目main.js,新增如下代码

import {getDict,getDictList} from '@/utils/getDict'
Vue.prototype.$getDict=getDict
Vue.prototype.$getDictList=getDictList

4. 页面使用

1. 表格中使用

表格中根据字典的key获取字典的name

  <el-table>
        <el-table-column label="状态" prop="status"  :formatter="(row, column) => $getDict(row, column, 'statusList')" />
  </el-table>

2. 表单中使用

表单中要通过下拉框的形式让用户选择字典

首先在data中声明变量

 data() {
      return {
        statusList:this.$getDictList('statusList')
      }
 }

然后在form中使用下拉框

     <el-form>         
    <el-form-item label="状态" prop="status">
           <el-select v-model="form.status" style="width: 100%" placeholder="请选择状态">
             <el-option
               v-for="item in statusList"
               :key="item.id"
               :label="item.name"
               :value="item.id"
             />
           </el-select>
         </el-form-item>
      </el-form>

二、定义动态字典

这里使用springboot、mysql生成字典后台接口

1. 新建数据库

image.png

CREATE TABLE `dict`  (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `parent_id` int(11) NULL DEFAULT 0 COMMENT '父主键',
  `dict_code` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '字典码',
  `dict_key` int(11) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '0' COMMENT '字典值',
  `dict_value` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '字典名称',
  `remark` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '字典备注',
  `is_deleted` int(2) NULL DEFAULT 0 COMMENT '是否已删除,0:正常,1:已删除',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1174 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '系统字典表' ROW_FORMAT = DYNAMIC;
SET FOREIGN_KEY_CHECKS = 1;

2. 生成Springboot接口

实体类Dict.java

@Entity
@Table(name = "dict")
@Data
public class Dict{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @ApiModelProperty(value = "主键" , example = "1")
    private Integer id;
    @ApiModelProperty(value = "父主键" , example = "1")
    private Integer pid;
    @ApiModelProperty(value = "字典码" , example = "1")
    private String code;
    @ApiModelProperty(value = "字典值" , example = "1")
    private Integer skey;
    @ApiModelProperty(value = "字典名称" , example = "1")
    private String svalue;
    @ApiModelProperty(value = "备注" , example = "1")
    private String remark;
    @ApiModelProperty(value = "是否删除" , example = "1")
    private Integer isdelete;
}

dao层

public interface DictDao extends JpaRepository<Dict, Integer> , JpaSpecificationExecutor<Dict>{
    List<Dict> findAllByPid(Integer pid);
    void deleteByPid(Integer pid);
    @Query(value="select * from dict where code=:code and isdelete=0 and pid!=0"
            ,nativeQuery=true)
    List<Dict> getDictByCode(@Param("code") String code);
}

service层

@Service
public class DictService{
    @Autowired
  private DictDao dictDao;
  public ResponseModel<Page<Dict>> page(String keywords, Pageable page) {
      Page<Dict> result = dictDao.findAll(new Specification<Dict>() {
            @Override
            public Predicate toPredicate(Root<Dict> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<Predicate>();
        list.add(cb.equal(root.get("pid").as(Integer.class), 0));
                if (!StringUtils.isEmpty(keywords)) {
                    //字典码
                    list.add(cb.like(root.get("code").as(String.class), "%" + keywords + "%"));
                    //字典名称
                    list.add(cb.like(root.get("svalue").as(String.class), "%" + keywords + "%"));
                    //备注
                    list.add(cb.like(root.get("remark").as(String.class), "%" + keywords + "%"));
                }
        Predicate[] p = new Predicate[list.size()];
        return cb.or(list.toArray(p));
            }
        }, page);
        return ResponseModel.success(result);
  }
  public ResponseModel<Dict> get(Integer id) {
    return ResponseModel.success(dictDao.findById(id).get());
  }
    public ResponseModel<List<Dict>> findList() {
    return ResponseModel.success(dictDao.findAll());
  }
  @Transactional
  public ResponseModel<Dict> save(Dict dict) {
      if(dict.getId()!=null){
          Dict dictOld = dictDao.findById(dict.getId()).orElse(null);
          if(dictOld!=null){
              UpdateUtil.copyNullProperties(dict,dictOld);
                return ResponseModel.success(dictDao.save(dictOld));
          }
      }
      return ResponseModel.success(dictDao.save(dict));
  }
  @Transactional
  public ResponseModel delete(String ids) {
    dictDao.deleteAllById(ConvertUtil.strToIntList(ids));
    return ResponseModel.success("删除成功");
  }
  @Transactional
  public ResponseModel saveBatch(List<Dict> dicts){
    if(dicts.size()>0){
      dictDao.deleteByPid(dicts.get(0).getPid());
      dictDao.flush();
      dictDao.saveAll(dicts);
    }
    return ResponseModel.success("保存成功");
  }
  public ResponseModel<List<Dict>> findAllByPid(Integer pid){
    return ResponseModel.success(dictDao.findAllByPid(pid));
  }
  public ResponseModel<Map<String,List<Dict>>> getDictByCode(String codes){
    String[] codeArr = codes.split(",");
    Map<String,List<Dict>> result = new HashMap<>();
    for(int i=0;i<codeArr.length;i++){
      result.put(codeArr[i],dictDao.getDictByCode(codeArr[i]));
    }
    return ResponseModel.success(result);
  }
}

Controller层

@RequestMapping(value = "/dict")
@RestController
@Api(value="接口",tags={"Dict()-增删改查;导入导出"})
public class DictController extends CommonController{
  @Autowired
  private DictService dictService;
  @ApiOperation(value = "获取分页数据" ,notes = "获取分页数据" )
  @ApiImplicitParams({
        @ApiImplicitParam(name = "keywords" ,value = "搜索关键字" , required = false, dataType = "String")
    })
    @PostMapping("/page")
    public ResponseModel<Page<Dict>> page(String keywords, Pageable page) {
        return dictService.page(keywords, page);
    }
    @ApiOperation(value = "获取列表数据" ,notes = "获取列表数据" )
  @GetMapping("/findAll")
  public ResponseModel<List<Dict>> findAll(){
    return dictService.findList();
  }
    @ApiOperation(value = "获取单条数据对象" ,notes = "获取单条数据对象")
  @ApiImplicitParams({
    @ApiImplicitParam(paramType = "query",name = "dictid" ,value = "dictID" , required = true, dataType = "Integer")
  })
  @GetMapping("/{id}")
    public ResponseModel<Dict> get(@PathVariable Integer id) {
    return dictService.get(id);
    }
    @ApiOperation(value = "保存单条数据", notes = "保存单条数据,id列为空则为新增,不为空则为修改")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Dict",value = "dict",required = false,dataType = "Dict")
    })
    @PostMapping("/save")
    public ResponseModel<Dict> save(Dict dict) {
    return dictService.save(dict);
    }
    @ApiOperation(value = "删除", notes = "删除" )
        @ApiImplicitParams({ @ApiImplicitParam(name = "dictids", value = "DictID", required = true, dataType = "String")
    })
    @RequestMapping(value = "/delete" ,method = { RequestMethod.DELETE})
    public ResponseModel delete(String dictids) {
       return dictService.delete(dictids);
    }
    @ApiOperation(value = "批量保存数据", notes = "批量保存数据,先删除,再保存")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Dict",value = "dict",required = false,dataType = "Arrays")
    })
    @PostMapping("/saveBatch")
    public ResponseModel<Dict> saveBatch(@RequestBody List<Dict> dicts) {
        return dictService.saveBatch(dicts);
    }
    @ApiOperation(value = "根据Pid查询字典", notes = "根据Pid查询字典")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pid",value = "pid",required = true,dataType = "Integer")
    })
    @PostMapping("/dictDetail")
    public ResponseModel<List<Dict>> findByPid(Integer pid) {
        return dictService.findAllByPid(pid);
    }
    @ApiOperation(value = "根据code获取字典列表", notes = "根据code获取字典列表,入参为多个code字符串")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "csode",value = "csode",required = true,dataType = "String")
    })
    @PostMapping("/getDictCode")
    public ResponseModel<Map<String,List<Dict>>> findByCode(String codes) {
      return dictService.getDictByCode(codes);
    }
}


目录
相关文章
|
JavaScript
VUE之vxe-table高级表格(表格内增删改、导入、导出、自定义打印、列设置隐藏显示等)用法
VUE之vxe-table高级表格(表格内增删改、导入、导出、自定义打印、列设置隐藏显示等)用法
8070 0
VUE之vxe-table高级表格(表格内增删改、导入、导出、自定义打印、列设置隐藏显示等)用法
|
7月前
【UI】 element ui 表格没有数据时用--填充
【UI】 element ui 表格没有数据时用--填充
175 2
|
7月前
|
JavaScript 前端开发
【vue】设计一个表格,增删改查,分页,固定列,特殊字符校验
【vue】设计一个表格,增删改查,分页,固定列,特殊字符校验
43 0
【vue】设计一个表格,增删改查,分页,固定列,特殊字符校验
|
JavaScript 前端开发 定位技术
JavaScript如何操作实现一个地图并标记到自身当前位置(本文从创建key值开始,到实现标点结束)
JavaScript如何操作实现一个地图并标记到自身当前位置(本文从创建key值开始,到实现标点结束)
131 0
JavaScript如何操作实现一个地图并标记到自身当前位置(本文从创建key值开始,到实现标点结束)
ECharts分段型视觉映射组件的属性修改
ECharts分段型视觉映射组件的属性修改
65 0
|
JavaScript 前端开发 API
Element表格和表单字典转换(静态和动态)(下)
Element表格和表单字典转换(静态和动态)(下)
203 0
|
JSON 前端开发 数据格式
前端(二十一):label语句、with语句、JSON、生成器、解析赋值、历史状态管理、将页面可编辑
label语句、with语句、JSON、生成器、解析赋值、历史状态管理、将页面可编辑
160 0
|
前端开发
【React工作记录三十八】对象的属性和值转换
【React工作记录三十八】对象的属性和值转换
75 0
|
JavaScript 前端开发
JavaScript通过改变location对象的hash属性实现相同页面显示不同详情内容的效果
JavaScript通过改变location对象的hash属性的应用 前面我们学到了BOM的Location对象,现在来讲一下实际的应用。通过改变hash属性获取不同的数据。 1.列表页面代码: &lt;a href=&quot;10模拟详情页面.html#0&quot; target=&quot;_blank&quot;&gt;张三&lt;/a&gt; &lt;a href=&quot;10模拟详情页面.html#1&quot; target=&quot;_blank&quot;&gt;李四&lt;/a&gt; &lt;a href=&quot;10模拟详情页面.html#2&quot; target=&quot;_blank&quot;&gt;王五&lt;/a&gt; &lt;a href=&quot;10模拟详情页面.html#3&quot; target=&quot;_b