关于Vue + element plus包装Component见解
关于Vue + element plus包装Component见解
一、关于编写思路
我以设计el-select选择框进行举例说明
父组件与Component传递params与Function使用Props传递,Component使用计算属性computed实现父组件modelValue与子组件modelValue值一致
二、父组件调用时代码编写
父组件所需要进行引入所包装组件、向其传入参数以及方法
<template>
<Component
ref="componentRef"
v-model="data"
:params="params"
:api="queryApi"
/>
</template>
<script lang="ts" setup>
// 将组件引入父组件
import Component from '组件路径'
// 父组件绑定数据
const data = ref(Class T)
// 定义组件Ref 以便能够使用组件抛出的Function、data
const componentRef = ref()
// 函数查询时所用参数
const params = ref(Class T)
// 父组件一个获取数据函数 函数由调用父组件定义以便后续调用时能够进行通用
const queryApi = () => {
}
</script>
三、包装组件代码编写
<template>
<el-select
v-model="data"
clearable
style="width: 100%"
value-key="key"
>
<el-option
v-for="item in optionList"
:value="item"
:label="item.label"
:key="item.key"
/>
</el-select>
</template>
<script setup lang="ts">
// 引入一个默认查询方法
import query from '查询方法路径'
// 一个名为 update:modelValue 的事件,当本地 ref 的值发生变更时触发。
const emit = defineEmits(['update:modelValue'])
// 声明Props 组件才能知道父组件使用props传递来的数据
const props = defineProps({
// 父组件调用组件时 v-model 绑定的属性值
modelValue: {
default: () => null,
type: Object,
},
// 父组件传递进来的api
api: {
default: () => null,
type: Function,
},
// 父组件传递进来查询参数
params: {
default: () => null,
type: Object,
},
// 初始化加载
requestAuto: {
default: () => true,
type: Boolean,
},
}
// 选择框option列表
const optionList = ref()
const data = computed({
// 当访问到data数据时调用,会获取父组件传递过来的属性值modelValue,并返回modelValue
get: () => {
return props.modelValue
},
// 当data数据被赋值时调用,data赋值val,通过emit方法触发了update:modelValue事件,将新的值val传递给父组件
set: (val) => {
emit('update:modelValue', val)
},
})
// 编写加载选项列表函数
const loadOptions = () => {
// 判断是都有方法传入
if(props.api){
props.api(props.params).then(res => {
}).catch(err => {
}).finally(() => {
}
}else{
query(props.params).then(res => {
}).catch(err => {
}).finally(() => {
}
}
}
// 是否进行初始化加载
props.requestAuto && loadData()
// 使用defineExpose 将组件方法、属性暴露给父组件 在不自动加载时能够进行加载数据
defineExpose({ loadOptions })
</script>

浙公网安备 33010602011771号