600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > vue form表单使用el-select下拉框 获取后台数据可供选择

vue form表单使用el-select下拉框 获取后台数据可供选择

时间:2022-08-22 03:21:06

相关推荐

vue form表单使用el-select下拉框 获取后台数据可供选择

文章目录

1. 前言2. 最终的效果3. 详细实现过程3.1 后端写一个获取数据的业务方法和controller接口3.2 vue前端获取数据进行展示

1. 前言

项目里本来录入新的激活码就是个el-input输入框,但是领导突然说这样每次输入不仅要从别处拿到激活码,还要确保不输错,很不友好,建议直接从数据库里获取所有能用的激活码,做个下拉框,直接下拉选中最好。那么,我们说干就干!

2. 最终的效果

直接上图:

3. 详细实现过程

3.1 后端写一个获取数据的业务方法和controller接口

特别简单,就是查数据库获取所有激活码装在list里进行返回。

xxxServiceImpl:

@Overridepublic List<String> findActiveCodes() {List<String> list = new ArrayList<>();Example oCode = new Example(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")public class ActiveCodeInfoController {...@GetMapping("/getActiveCodes")public ResponseBean getActiveCodes() {logger.info("getCode function ...");List<String> activeCodeList = activeCodeInfoService.findActiveCodes();return ResponseBean.success(activeCodeList);}}

ResponseBean是全局封装的返回数据的格式,可以不用管,你直接返回list。

封装的返回格式

{"success": true,"data": {"code1","code2",...}}

3.2 vue前端获取数据进行展示

由第一步我们得知,访问后台接口的URL:

url = “business/activeCode/getActiveCodes”

① 写一个空列表options用来装数据:

export default {data() {return {options: [], // 列表数据,存放获取的激活码}}}

②再写一个method:

async getOptions() {const {data: res} = await this.$http.get("business/activeCode/getActiveCodes",{});if (!res.success) {return this.$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,以上就是实现获取后台数据下拉框的全部内容。

另,掩码方法实现很简单,看这里即可。

每天一小步。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。