问题例子
- 原组件 MyTable.vue
<template>
<table ref="table" @cellClick="handleCellClick"></table>
</template>
<script>
export default {
props: {
tools: {
type: Array,
default: () => []
},
columns: {
type: Array,
default: () => [],
require: true
},
customs: {
type: Array,
default: () => []
},
validRules: {
type: Object,
default: () => {}
}
},
methods: {
handleCellClick() {
this.$emit("cellClick");
},
clearTable() {
this.$refs.table.clearTable()
}
}
};
</script>
- 二次封装 MyChildTable.vue
<template>
<my-table
ref="myTable"
:tools="tools"
:columns="columns"
:customs="customs"
:validRules="validRules"
></my-table>
</template>
<script>
export default {
props: {
tools: {
type: Array,
default: () => []
},
columns: {
type: Array,
default: () => [],
require: true
},
customs: {
type: Array,
default: () => []
},
validRules: {
type: Object,
default: () => {}
}
},
methods: {
handleCellClick() {
this.$emit("cellClick");
},
clearTable() {
this.$refs.myTable.clearTable()
}
}
};
</script>
- 使用二次封装组件 MyPage.vue
<template>
<my-child-table
ref="myChildTable"
:tools="tools"
:columns="columns"
:customs="customs"
:validRules="validRules"
@cellClick="handleCellClick"
></my-child-table>
</template>
<script>
export default {
data: {
tools: [{ name: "add", title: "新增" }],
columns: [{ field: "id", title: "ID编号" }],
customs: [],
validRules: {
id: [{ required: true, message: "请输入ID编码" }]
}
},
methods: {
handleCellClick() {
// 页面业务逻辑
},
clearTable() {
this.$refs.myChildTable.clearTable()
}
}
};
</script>
问题描述
我在实际开发中二次封装完组件之后使用,发现不太好维护. 上面这个例子只是简单的写出来表达这种情况,实际上开发出来的有更多的 props 以及事件. 还有类似情况就是二次封装第三方的组件的时候,那些第三方组件有很多的 props,methods,还有很多事件. 有没有办法能够更方便简单的二次封装,类似把原组件的 props,methods,事件这些都继承? 目前我二次封装都是把原组件的这些 props 参数一个个的定义,然后传入;再把原组件的事件也一个个 emit 出来,然后在新组件里接收了再 emit 出去. 还有原组件有的那些方法还要加ref去获取重新定义,我感觉这样很麻烦,而且不太好维护,自己也找了解决方法,但是没找到,所以请教一下各位有没有比较好的二次封装方法?