聽風說 2021-11-17 11:39 采纳率: 80%
浏览 60

Vue二次封装组件怎么能快速继承原组件的属性,方法和事件?

问题例子

  1. 原组件 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>
  1. 二次封装 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>
  1. 使用二次封装组件 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去获取重新定义,我感觉这样很麻烦,而且不太好维护,自己也找了解决方法,但是没找到,所以请教一下各位有没有比较好的二次封装方法?

  • 写回答

1条回答 默认 最新

  • 前端纸飞机 前端领域优质创作者 2021-11-17 19:07
    关注

    async

    评论

报告相同问题?

问题事件

  • 创建了问题 11月17日

悬赏问题

  • ¥15 is not in the mmseg::model registry。报错,模型注册表找不到自定义模块。
  • ¥15 安装quartus II18.1时弹出此error,怎么解决?
  • ¥15 keil官网下载psn序列号在哪
  • ¥15 想用adb命令做一个通话软件,播放录音
  • ¥30 Pytorch深度学习服务器跑不通问题解决?
  • ¥15 部分客户订单定位有误的问题
  • ¥15 如何在maya程序中利用python编写领子和褶裥的模型的方法
  • ¥15 Bug traq 数据包 大概什么价
  • ¥15 在anaconda上pytorch和paddle paddle下载报错
  • ¥25 自动填写QQ腾讯文档收集表