问题背景
公司的后台项目使用的是 Ant Design Vue框架。 为更方便开发,项目我们的项目对Ant Design Vue部分常用的组件进行了二次封装,例如Table组件,封装了原本的分页查询、表格数据多选等逻辑,便于开发时不用考虑很多复用的逻辑。本文中奖经过二次封装的Table组件命名为BaseTable组件
问题背景
之前二次封装的组件知考虑了主要常用的几个属性配置,由父组件通过props传递给BaseTable组件,再由BaseTable组件为props参数进行处理并传到Table组件中,而原本的Table组件中有非常多的配置属性都没有做封装处理,等需要使用的时候还需要重编辑封装好的组件非常麻烦。
解决方法
可以利用组件传值的Attributes,父组件给二次封装的子组件传值,如果子组件没有使用props接收这些属性,则可以回被存储到子组件的Attributes属性中。在子组件中使用useAttrs(),可以获取未被props接收的其他属性。再使用v-bind奖Attributes值传递给原生组件中即可。
代码示例如下
<!-- 父组件 -->
<template>
<div class="">
<div @click="changeA">修改aaa</div>
<testAttribute name="testName" @testFunc="testFunc" :aaa="aaa" bbb="bbb" />
</div>
</template>
<script setup lang="ts">
import testAttribute from './components/testAttribute.vue'
import { ref } from 'vue'
const aaa = ref('aaa')
function testFunc() {
console.log('testFunc')
}
function changeA() {
aaa.value = 'changeA'
}
</script>
<style scoped lang="less"></style>
<!-- 二次封装的子组件 -->
<template>
<div class="">
<div class="">testAttribute</div>
<Child v-bind="attrs"></Child>
</div>
</template>
<script setup lang="ts">
import Child from './Child.vue'
import { onMounted, useAttrs } from 'vue'
const attrs = useAttrs()
onMounted(() => {
console.log('attrs', attrs.name)
})
</script>
<style scoped lang="less"></style>
<!-- 最里面的原生组件 -->
<template>
<div class="">
<div class="">这是child组件</div>
<div class="">{{ name }}</div>
<div class="">{{ aaa }}</div>
</div>
</template>
<script setup lang="ts">
import { onMounted, useAttrs } from 'vue'
const props = defineProps({
name: String,
aaa: String,
})
const attrs = useAttrs()
onMounted(() => {
console.log('子组件attrs', attrs)
})
</script>
<style scoped lang="less"></style>
父组件奖属性aaa、bbb和方法testFunc 传递给子组件,子组件微使用props接收这些数据,并使用const attrs = useAttrs()获取传递缓过来的属性,最后再使用v-bind:<Child v-bind="attrs"></Child> 将Attributes属性传给内部的子组件。内部的子组件就可以接收传过来的属性了。
非特殊说明,本博所有文章均为博主原创。
如若转载,请注明出处:https://webxbz.com/98
共有 0 条评论