1. 前言
项目里本来录入新的激活码就是个el-input输入框,但是领导突然说这样每次输入不仅要从别处拿到激活码,还要确保不输错,很不友好,建议直接从数据库里获取所有能用的激活码,做个下拉框,直接下拉选中最好。那么,我们说干就干!
2. 最终的效果
直接上图:
3. 详细实现过程
3.1 后端写一个获取数据的业务方法和controller接口
特别简单,就是查数据库获取所有激活码装在list里进行返回。
xxxServiceImpl:
@OverridepublicList<String>findActiveCodes(){List<String> list=newArrayList<>();Example oCode=newExample(ActiveCodeInfo.class);Example.Criteria criteriaCode= oCode.createCriteria();
criteriaCode.andNotEqualTo("status",0);List<ActiveCodeInfo> activeCodeInfos= activeCodeInfoMapper.selectByExample(oCode);for(int i=0; i< activeCodeInfos.size(); i++){String active_code= activeCodeInfos.get(i).getActive_code();
list.add(active_code);}return list;}
xxxController:
@RestController@RequestMapping("/business/activeCode")publicclassActiveCodeInfoController{...@GetMapping("/getActiveCodes")publicResponseBeangetActiveCodes(){
logger.info("getCode function ...");List<String> activeCodeList= activeCodeInfoService.findActiveCodes();returnResponseBean.success(activeCodeList);}}
ResponseBean是全局封装的返回数据的格式,可以不用管,你直接返回list。
封装的返回格式
{"success":true,"data":{"code1","code2",...}}
3.2 vue前端获取数据进行展示
由第一步我们得知,访问后台接口的URL:
url = “business/activeCode/getActiveCodes”
① 写一个空列表options用来装数据:
exportdefault{data(){return{options:[],// 列表数据,存放获取的激活码}}}
②再写一个method:
asyncgetOptions(){const{data: res}=awaitthis.$http.get("business/activeCode/getActiveCodes",{});if(!res.success){returnthis.$message.error("获取激活码失败:"+res.data.errorMsg);}else{
console.log(res);this.options= res.data;// 这里与你返回的数据装配格式有关
console.log(this.options);}},
③ created()方法内初始化就加载拿到后台数据:
created(){this.getOptions();}
④ 然后是最终的form表单里el-select框引入:
<el-row><el-col:span="12"><el-form-item label="激活码" prop="active_code"><el-select v-model="addRuleForm.active_code" placeholder="请选择"><el-option v-for="item in options":value="item">{{codeMask(item)}}</el-option></el-select><!--<el-input placeholder="输入激活码内容" v-model="addRuleForm.active_code"></el-input>--></el-form-item></el-col></el-row>
关键代码是:
<el-option v-for="item in options":value="item">{{codeMask(item)}}// 此处无其他需求你可以直接写 item 我这里是将item传入 codeMask方法做了掩码处理。</el-option>
OK,以上就是实现获取后台数据下拉框的全部内容。
另,掩码方法实现很简单,看这里即可。
每天一小步。