前端Vue:使用函数化组件及createElement()函数封装表格

185 阅读3分钟

image.png

什么是函数式组件

对于函数式组件,可以这样定义: 我们可以把函数式组件想像成组件里的一个函数,入参是渲染上下文(render context),返回值是渲染好的HTML

  • Stateless(无状态):组件自身是没有状态的
  • Instanceless(无实例):组件自身没有实例,也就是没有this

由于函数式组件拥有的这两个特性,我们就可以把它用作高阶组件(High order components),所谓高阶,就是可以生成其它组件的组件。就像日本的高精度的母机。

基本写法:

image.png 因为函数式组件没有 this,参数就是靠 context 来传递的了,有如下字段的对象:

  • props:提供所有 prop 的对象
  • childrenVNode 子节点的数组
  • slots:一个函数,返回了包含所有插槽的对象
  • scopedSlots:(2.6.0+) 一个暴露传入的作用域插槽的对象。也以函数形式暴露普通插槽。
  • data:传递给组件的整个数据对象,作为 createElement 的第二个参数传入组件
  • parent:对父组件的引用
  • listeners:(2.3.0+) 一个包含了所有父组件为当前组件注册的事件监听器的对象。这是 data.on 的一个别名。
  • injections:(2.3.0+) 如果使用了 inject 选项,则该对象包含了应当被注入的 property。

挂载阶段与模版模式的对比 image.png

createElement()参数

这里是 createElement 接受的参数:

// @returns {VNode}
createElement(
  // {String | Object | Function}
  // 一个 HTML 标签名、组件选项对象,或者
  // resolve 了上述任何一种的一个 async 函数。必填项。
  'div',

  // {Object}
  // 一个与模板中属性对应的数据对象。可选。
  {
    // (详情见下一节)
  },

  // {String | Array}
  // 子级虚拟节点 (VNodes),由 `createElement()` 构建而成,
  // 也可以使用字符串来生成“文本虚拟节点”。可选。
  [
    '先写一些文字',
    createElement('h1', '一则头条'),
    createElement(MyComponent, {
      props: {
        someProp: 'foobar'
      }
    })
  ]
)

image.png

深入数据对象

```
  {
    // 与 `v-bind:class` 的 API 相同,
    // 接受一个字符串、对象或字符串和对象组成的数组
    'class': {
      foo: true,
      bar: false
    },
    // 与 `v-bind:style` 的 API 相同,
    // 接受一个字符串、对象,或对象组成的数组
    style: {
      color: 'red',
      fontSize: '14px'
    },
    // 普通的 HTML 特性
    attrs: {
      id: 'foo'
    },
    // 组件 prop
    props: {
      myProp: 'bar'
    },
    // DOM 属性
    domProps: {
      innerHTML: 'baz'
    },
    // 事件监听器在 `on` 属性内,
    // 但不再支持如 `v-on:keyup.enter` 这样的修饰器。
    // 需要在处理函数中手动检查 keyCode。
    on: {
      click: this.clickHandler
    },
    // 仅用于组件,用于监听原生事件,而不是组件内部使用
    // `vm.$emit` 触发的事件。
    nativeOn: {
      click: this.nativeClickHandler
    },
    // 自定义指令。注意,你无法对 `binding` 中的 `oldValue`
    // 赋值,因为 Vue 已经自动为你进行了同步。
    directives: [
      {
        name: 'my-custom-directive',
        value: '2',
        expression: '1 + 1',
        arg: 'foo',
        modifiers: {
          bar: true
        }
      }
    ],
    // 作用域插槽的格式为
    // { name: props => VNode | Array<VNode> }
    scopedSlots: {
      default: props => createElement('span', props.text)
    },
    // 如果组件是其它组件的子组件,需为插槽指定名称
    slot: 'name-of-slot',
    // 其它特殊顶层属性
    key: 'myKey',
    ref: 'myRef',
    // 如果你在渲染函数中给多个元素都应用了相同的 ref 名,
    // 那么 `$refs.myRef` 会变成一个数组。
    refInFor: true
  }
```

函数化组件在二次封装el-table的实践

image.png

const createColumn = (h, columnConfig, isPaginationTable, context, store)=> {
    const { columnProps, render, children, editTooltipData, unsortable } = columnConfig;
    let toolTilInfo = store?.getters?.tooltipList(editTooltipData);
    let info = toolTilInfo?.info;
    let code = toolTilInfo?.code;
    let userRole = store?.getters?.userRole;
    let option = {
        props: { ...columnProps },
        scopedSlots: {},
        key: columnProps.label + userRole + code + info
    };
    if (render) {
        option.scopedSlots.default = (props) => {
            return render(h, props.row, props.column);
        };
    } else {
        option.scopedSlots.default = ({ row, column, $index }) => {
            const { formatter, prop } = columnProps;
            const val = formatter ? formatter(row, column, row[prop], $index) : row[prop];
            return h('span', {}, [dealNull(val)]);
        };
    }
    if (info) {
        option.props.renderHeader = (h, { column, $index }) => {
            return [
                columnProps.renderHeader
                    ? columnProps.renderHeader(h, { column, $index })
                    : column.label,
                createColTooltip(h, info),
                userRole === 'admin'
                    ? createEdit(h, info, editTooltipData, context, userRole)
                    : null
            ];
        };
    }
    if (!isPaginationTable && !children?.length && !unsortable) {
        option.props.sortable = true;
        option.props.sortMethod = (x, y) => {
            if (parseFloat(x[columnProps.prop]) == x[columnProps.prop]) {
                const xVal = isNum(x[columnProps.prop])
                    ? parseFloat(x[columnProps.prop])
                    : Number.MIN_VALUE;
                const yVal = isNum(y[columnProps.prop])
                    ? parseFloat(y[columnProps.prop])
                    : Number.MIN_VALUE;
                return xVal - yVal;
            } else {
                return x[columnProps.prop].localeCompare(y[columnProps.prop], 'zh-CN');
            }
        };
    }
    let childNodes = [];
    if (children?.length) {
        childNodes = children.map((column) => {
            return createColumn(h, column);
        });
    }
    console.log(option);
    return h('el-table-column', option, childNodes);
};
const dealNull = (val) => {
    return val || (val === 0 ? 0 : ' - ');
};

const createColTooltip = (h, info) =>
    h('el-tooltip', { props: { effect: 'light' } }, [
        h('i', { class: 'col-tooltip' }),
        h('span', { slot: 'content', domProps: { innerHTML: info } })
    ]);

const createEdit = (h, info, editTooltipData, context, userRole) => {
    let self = this;
    return h('i', {
        class: 'el-icon-edit',
        style: {
            marginLeft: '6px',
            fontSize: '12px'
        },
        on: {
            click(h) {
                context.parent.editTooltip(info, editTooltipData);
            }
        }
    });
};

相关知识点