封装通用组件

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

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

一、数据从父组件传入this

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

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

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

二、在父组件处理事件it

在通用组件中,一般须要处理各类事件,通用组件只做为一个中转,事件的处理方法应当尽可能放在父组件中。例如:io

在子组件中的方法:table

handleSelectionChange(val) {
        const selectionArr = [];
        val.forEach(function (el) {
                selectionArr.push(el);
         });
         this.$emit('commitSelection', selectionArr);
          /*向父组件传递的数据:commitSelection  被选中的数据 */
   },
在父组件中处理:
  <my-table ref='table' @commitSelection='commitSelection'></my-table>
这样下降了耦合,也保证了通用组件的数据不被污染。不过,不是全部的事件都放在父组件中处理的。例如组件内部的一些交互行为,或者处理组件内部数据的传递,这就不须要在父组件中处理。
三、留一个slot
相关文章
相关标签/搜索