vue中下拉框组件的封装方式

vue下拉框组件的封装

原理

vue element中,需要封装一个对应的下拉款组件。

第一步:在api_domain.js中添加后台的请求接口

//获取下拉框的接口 从redis中
 domainGetDomainKeyRedis: params => { 
	 return axios.post('domain-manager/domain/getDomainKeyRedis',qs.stringify(params));
},

//获取下拉框的接口 从DB中
 domainGetDomainKeyDB: params => { 
	 return axios.post('domain-manager/domain/getDomainKeyDB',qs.stringify(params));
},

第二步,在文件夹api中新建getSelect.js,内容

/**
 * _this为传过来的this
 * 
 * 根据参数str,去获取到对应的下拉框的值
 * 
 * paramName,接收的数组,如'type'
 * 
 * 先去redis总查询,如果没有值,再去数据库中查询
 */
import api from '@/api/api_domain'


export function GetSelect(_this,str,paramName) {
	
 let para = {
	key: str
	};
	
	if(typeof str === "undefined" || str == ""){
	//	return options;
	}else{
	_this.$api.domain.domainGetDomainKeyRedis(para).then((res) => {
	
	_this[paramName] = res.data.data.listDomainDefine;
	
	}).catch((err)=>{
	    console.log(err);
	  });
	}
}

使用

引入js

import {GetSelect} from '@/api/getSelect'

取值

//获取资源类型GetSelect(this,'resType','type');

resType,是传递到后台方法的查询条件,

就是在【域定义管理】中简称,点击【域值】按钮可看到对应的下拉框数据

type,是接受查询出的list的参数,在页面中我定义了type: [],用来接收,资源类型下拉框中的值

在页面中

<el-form-item label="类型" prop="resType">	
	<el-select v-model="addForm.resType" filterable placeholder="请选择" style="width:100%">
	<el-option v-for="item in type" :key="item.key " :label="item.name" :value="item.key">
	</el-option>
	</el-select>	
</el-form-item>

在table中怎么去显示类型为中文名称

<el-table-column prop="ptType" label="类型" min-width="10%" :formatter="formatType" >
	</el-table-column>

注意: :formatter=“formatType”

然后写一个方法formatType

formatType: function (row, column) {//类型转换
	
	for(var a = 0 ;a< this.options.length ; a++){
	if(row.ptType == this.options[a].key){
	return this.options[a].name;
	}
	}
	
	},

vue封装远程下拉框组件

之前封装了一个远程搜索的输入框,静态在Vue官网看到一个类似的远程搜索下拉框,今天也封装一个远程搜索下拉框,面对不同的需求

我们修改了官方提供的代码来封装了

父组件

RemoteSearch.vue

vue的参数是可以通过封装在props内,被其他界面引用

注意:

一:js中在调用json格式数组的值的时候——有两种形式

以下为dataList数组

  • 形式一:dataList[0].name
  • 形式二:dataList[0][name]

在有些时候会把**.变量**识别成调用,所以在一些情况下使用第二个效果更好

js的数组手动设置值(给dataList设置一个value值)

dataList.value = ?

以下为引用的vue界面

<template>
 <div>
 <RemoteSearch :choose-flag="0" :auto-complete-column="name" ref="refreshData"></RemoteSearch>
 <el-button type="primary" @click="refreshChartSearch" style="margin-left: 10px">重置</el-button>
 </div>
</template>

<script>
import RemoteSearch from "@/components/select/RemoteSearch";
export default {
 components: {
 RemoteSearch
 },
 data(){
 return {
 }
 },
 methods:{
 refreshChartSearch(){
 this.$nextTick(() => {
 this.$refs.refreshData.refreshData();
 //DOM渲染完毕后就能正常获取了
 })
 },
 },
}
</script>

<style scoped>

</style>

只需要通过import导入对应的组件,通过components来调用,并通过类似标签的形式来声明

子组件通过父组件提供的props的参数重写(修改)父组件的参数

如果子组件不调用,props的参数就会是默认的值。

子组件可以通过在标签内使用:特定值的方式来修改值

重置的按钮实现,可以参考之前封装远程搜索输入框的帖子

这里父组件的placeholder也可以做成让子组件自己选择的,但是我这里的形式比较通用,就没有修改,有兴趣的可以自行优化

placeholder="请输入内容"

总结

作者:田湖_怎么了原文地址:https://blog.csdn.net/qq_34652478/article/details/100929023

%s 个评论

要回复文章请先登录注册