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

得意时要看淡,失意时要看开。不论得意失意,切莫大意;不论成功失败,切莫止步。志得意满时,需要的是淡然,给自己留一条退路;失意落魄时,需要的是泰然,给自己觅一条出路vue form表单使用el-select下拉框 获取后台数据可供选择,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

1. 前言

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

2. 最终的效果

直接上图:
在这里插入图片描述

3. 详细实现过程

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

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

xxxServiceImpl:

@Override
public 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,以上就是实现获取后台数据下拉框的全部内容。

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


每天一小步。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/157241.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!