封装通用组件

最近因项目需求,对ElementUI中表格、对话框、菜单等做了二次封装,为了较少代码的书写量等。

通用组件具备高性能、低耦合的特性。

1、数据从父组件传入

为了解耦,子组件本身不能生成数据;即使生成了数据,也只能组件内使用,不能传递出去。

父组件对子组件传参,使用props,例如:

 props: {
            slides: {
                type: Array,
                default: []
            },
            autoplay: {
                type: Boolean,
                default: true
            },
            height: {
                type: String,
                default: "400px"
            },
            arrow: {
                type: String,
                default: "hover"
            }
   }

2、在父组件处理事件

在通用组件中,通常需要处理各种事件,通用组件只作为一个中转,事件的处理方法应当尽量放在父组件中。例如:

在子组件中的方法:

handleSelectionChange(val) {
        const selectionArr = [];
        val.forEach(function (el) {
                selectionArr.push(el);
         });
         this.$emit('commitSelection', selectionArr);
          /*向父组件传递的数据:commitSelection  被选中的数据 */
   },
在父组件中处理:
  <my-table ref='table' @commitSelection='commitSelection'></my-table>
这样降低了耦合,也保证了通用组件的数据不被污染。不过,不是所有的事件都放在父组件中处理的。例如组件内部的一些交互行为,或者处理组件内部数据的传递,这就不需要在父组件中处理。
3、留一个slot
 
原文地址:https://www.cnblogs.com/happybread/p/9516791.html