Vue 用createElement 自定义列表头

た 入场券 2022-10-11 13:57 396阅读 0赞

文章目录

    • Vue 用createElement 自定义列表头
      • 一、前言
      • 二、需求实现效果
      • 三、知识点
        • 1、createElement 参数
          • 深入 data 对象
        • 2、createElement 创建元素过程
      • 四、具体实现及代码
        • 1、第一步:创建需要自定义列表头的table
        • 二、第二步:创建自定义组件封装el-popover
        • 三、局部注册组件并手写createElement
      • 五、扩展知识点
        • 1、Vue源码9个基础方法

Vue 用createElement 自定义列表头

一、前言

最近产品有需求,想要把一个搜索框放入到列表头中,一般的属性无法满足我们这个需求,所以我们需要使用自定义表头。

现阶段我比较常用的table有 elementUI 的 el-table、umy-ui的u-table和 vxe-table的vxe-grid。

u-table和el-table都有提供 render-header 方便我们自定义表头。而 vxe-table 则提供了更多渲染器可以方便我们进行操作,详情可以看官方文档。这里我主要用的是umy-ui的u-table。

二、需求实现效果

在这里插入图片描述

三、知识点

1、createElement 参数

createElement 参数

接下来你需要熟悉的是如何在createElement函数中生成模板。这里是createElement接受的参数:

  1. // @returns {VNode}
  2. createElement(
  3. // {String | Object | Function}
  4. // 一个 HTML 标签字符串,组件选项对象,或者一个返回值
  5. // 类型为 String/Object 的函数,必要参数
  6. 'div',
  7. // {Object}
  8. // 一个包含模板相关属性的数据对象
  9. // 这样,您可以在 template 中使用这些属性。可选参数。
  10. {
  11. // (详情见下一节)
  12. },
  13. // {String | Array}
  14. // 子节点 (VNodes),由 `createElement()` 构建而成,
  15. // 或使用字符串来生成“文本节点”。可选参数。
  16. [
  17. '先写一些文字',
  18. createElement('h1', '一则头条'),
  19. createElement(MyComponent, {
  20. props: {
  21. someProp: 'foobar'
  22. }
  23. })
  24. ]
  25. )
深入 data 对象

有一件事要注意:正如在模板语法中,v-bind:classv-bind:style,会被特别对待一样,在 VNode 数据对象中,下列属性名是级别最高的字段。该对象也允许你绑定普通的 HTML 特性,就像 DOM 属性一样,比如innerHTML(这会取代v-html指令)。

  1. {
  2. // 和`v-bind:class`一样的 API
  3. 'class': {
  4. foo: true,
  5. bar: false
  6. },
  7. // 和`v-bind:style`一样的 API
  8. style: {
  9. color: 'red',
  10. fontSize: '14px'
  11. },
  12. // 正常的 HTML 特性
  13. attrs: {
  14. id: 'foo'
  15. },
  16. // 组件 props
  17. props: {
  18. myProp: 'bar'
  19. },
  20. // DOM 属性
  21. domProps: {
  22. innerHTML: 'baz'
  23. },
  24. // 事件监听器基于 `on`
  25. // 所以不再支持如 `v-on:keyup.enter` 修饰器
  26. // 需要手动匹配 keyCode。
  27. on: {
  28. click: this.clickHandler
  29. },
  30. // 仅对于组件,用于监听原生事件,而不是组件内部使用
  31. // `vm.$emit` 触发的事件。
  32. nativeOn: {
  33. click: this.nativeClickHandler
  34. },
  35. // 自定义指令。注意,你无法对 `binding` 中的 `oldValue`
  36. // 赋值,因为 Vue 已经自动为你进行了同步。
  37. directives: [
  38. {
  39. name: 'my-custom-directive',
  40. value: '2',
  41. expression: '1 + 1',
  42. arg: 'foo',
  43. modifiers: {
  44. bar: true
  45. }
  46. }
  47. ],
  48. // Scoped slots in the form of
  49. // { name: props => VNode | Array<VNode> }
  50. scopedSlots: {
  51. default: props => createElement('span', props.text)
  52. },
  53. // 如果组件是其他组件的子组件,需为插槽指定名称
  54. slot: 'name-of-slot',
  55. // 其他特殊顶层属性
  56. key: 'myKey',
  57. ref: 'myRef'
  58. }

2、createElement 创建元素过程

  • Vue 利用 createElement 方法创建 VNode,定义在 src/core/vdom/crate-element.js 中:

    // wrapper function for providing a more flexible interface
    // without getting yelled at by flow
    export function createElement (
    context: Component,
    tag: any,
    data: any,
    children: any,
    normalizationType: any,
    alwaysNormalize: boolean
    ): VNode | Array {
    // 这些都只是判断,可以无视
    if (Array.isArray(data) || isPrimitive(data)) {

    1. normalizationType = children
    2. children = data
    3. data = undefined

    }
    // 这些都只是判断,可以无视
    if (isTrue(alwaysNormalize)) {

    1. normalizationType = ALWAYS_NORMALIZE

    }
    return _createElement(context, tag, data, children, normalizationType)
    }

  • createElement 方法实际上是对 _createElement 方法的封装,它允许传入的参数更加灵活,在处理这些参数后,调用真正创建 VNode 的函数 _crateElement :

    export function createElement (
    context: Component,
    tag?: string | Class | Function | Object,
    data?: VNodeData,
    children?: any,
    normalizationType?: number
    ): VNode | Array {
    // 只是一些判断,如果出问题了,就创建一个空的元素
    if (isDef(data) && isDef((data: any)._ob
    )) {

    1. process.env.NODE_ENV !== 'production' && warn(
    2. `Avoid using observed data object as vnode data: ${ JSON.stringify(data)}\n + 'Always create fresh vnode data objects in each render!', context // 这里\n后面应该有个`,但是不知道为什么会导致整个页面一片红,所以去掉了
    3. )
    4. // 如果传进来的VNodeData为undefined,则返回空元素
    5. return createEmptyVNode()

    }
    // 获取 VNodeData类型
    // object syntax in v-bind
    if (isDef(data) && isDef(data.is)) {

    1. tag = data.is

    }
    if (!tag) {

    1. // in case of component :is set to falsy value
    2. return createEmptyVNode()

    }
    // 一些判断,可以无视
    // warn against non-primitive key
    if (process.env.NODE_ENV !== ‘production’ &&

    1. isDef(data) && isDef(data.key) && !isPrimitive(data.key)

    ) {

    1. if (!__WEEX__ || !('@binding' in data.key)) {
    2. warn(
    3. 'Avoid using non-primitive value as key, ' +
    4. 'use string/number value instead.',
    5. context
    6. )
    7. }

    }
    // support single function children as default scoped slot
    if (Array.isArray(children) &&

    1. typeof children[0] === 'function'

    ) {

    1. data = data || { }
    2. data.scopedSlots = { default: children[0] }
    3. children.length = 0

    }
    // children 的规范化
    //类型不同规范的方法也就不一样,它主要是参考 render 函数是编译生成的还是用户手写的。
    if (normalizationType === ALWAYS_NORMALIZE) {

    1. // 用户手写的
    2. children = normalizeChildren(children)

    } else if (normalizationType === SIMPLE_NORMALIZE) {

    1. // render 函数是编译生成
    2. children = simpleNormalizeChildren(children)

    }
    // 经过对 children 的规范化,children 变成了一个类型为 VNode 的 Array
    let vnode, ns

    // 这里先对 tag 做判断,如果是 string 类型,则接着判断如果是内置的一些节点,则直接创建一个普通 VNode,
    // 如果是为已注册的组件名,则通过 createComponent 创建一个组件类型的 VNode,否则创建一个未知的标签的 VNode。
    //如果是 tag 一个 Component 类型,则直接调用 createComponent 创建一个组件类型的 VNode 节点。
    //对于 createComponent 创建组件类型的 VNode 的过程,之后再去写,本质上它还是返回了一个 VNode。

    if (typeof tag === ‘string’) {

    1. let Ctor
    2. ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag)
    3. if (config.isReservedTag(tag)) {
    4. // platform built-in elements
    5. if (process.env.NODE_ENV !== 'production' && isDef(data) && isDef(data.nativeOn) && data.tag !== 'component') {
    6. warn(
    7. `The .native modifier for v-on is only valid on components but it was used on <${ tag}>.`,
    8. context
    9. )
    10. }
    11. // 如果是 string 类型,则接着判断如果是内置的一些节点,则直接创建一个普通 VNode
    12. vnode = new VNode(
    13. config.parsePlatformTagName(tag), data, children,
    14. undefined, undefined, context
    15. )
    16. } else if ((!data || !data.pre) && isDef(Ctor = resolveAsset(context.$options, 'components', tag))) {
    17. // 是为已注册的组件名,则通过 createComponent 创建一个组件类型的 VNode
    18. // component
    19. vnode = createComponent(Ctor, data, context, children, tag)
    20. } else {
    21. // 否则创建一个未知的标签的 VNode
    22. // unknown or unlisted namespaced elements
    23. // check at runtime because it may get assigned a namespace when its
    24. // parent normalizes children
    25. vnode = new VNode(
    26. tag, data, children,
    27. undefined, undefined, context
    28. )
    29. }

    } else {

    1. // 如果是 tag 一个 Component 类型,则直接调用 createComponent 创建一个组件类型的 VNode 节点。
    2. // 这里就是通过createElement 创建组件
    3. // 本质上它还是返回了一个 VNode。
    4. // direct component options / constructor
    5. vnode = createComponent(tag, data, context, children)

    }
    if (Array.isArray(vnode)) {

    1. return vnode

    } else if (isDef(vnode)) {

    1. if (isDef(ns)) applyNS(vnode, ns)
    2. if (isDef(data)) registerDeepBindings(data)
    3. return vnode

    } else {

    1. return createEmptyVNode()

    }
    }

_createElement这个函数可以提供创建元素和创建组件两个功能。但是我们这里主要看创建元素的功能

  1. // src/core/vdom/crate-element.js
  2. // 创建空元素
  3. export const createEmptyVNode = (text: string = '') => {
  4. const node = new VNode()
  5. node.text = text
  6. node.isComment = true
  7. return node
  8. }

_createElement 方法有 5 个参数:

  • context 表示 VNode 的上下文环境,它是 Component 类型;
  • tag 表示标签,它可以是一个字符串,也可以是一个 Component;
  • data 表示 VNode 的数据,它是一个 VNodeData 类型,可以在 flow/vnode.js 中找到他的定义;
  • children 表示当前 VNode 的子节点,它是任意类型的,接下来需要被规范为标准的 VNode 数组;
  • normalizationType 表示子节点规范的类型,类型不同规范的方法也就不一样,它主要是参考 render 函数是编译生成的还是用户手写的。

children 的规范化

  • 由于 Virtual DOM 实际上是一个树状结构,每一个 VNode 可能会有若干个子节点,这些子节点应该也是 VNode 的类型。_createElement 接收的第 4 个参数 children 是任意类型的,因为就需要把它们规范成 VNode 类型。
  • 这里会根据 normalizationType 的不同,调用了 normaliza(children) 和 simpleNormalizeChildren(children) 方法,定义在 src/core/vdom/helpers/normalzie-children.js 中:

    // The template compiler attempts to minimize the need for normalization by
    // statically analyzing the template at compile time.
    //
    // For plain HTML markup, normalization can be completely skipped because the
    // generated render function is guaranteed to return Array. There are
    // two cases where extra normalization is needed:

    // 1. When the children contains components - because a functional component
    // may return an Array instead of a single root. In this case, just a simple
    // normalization is needed - if any child is an Array, we flatten the whole
    // thing with Array.prototype.concat. It is guaranteed to be only 1-level deep
    // because functional components already normalize their own children.
    // 当子节点包含组件时 - 因为功能组件可能返回一个数组而不是单个根节点元素。
    // 在这种情况下,只需要一个简单的规范化——如果有任何子节点是一个数组,
    // 我们用 Array.prototype.concat 将整个事物展平。
    // 它保证只有 1 级深度,因为功能组件已经规范了他们自己的子元素。
    export function simpleNormalizeChildren (children: any) {
    for (let i = 0; i < children.length; i++) {

    1. if (Array.isArray(children[i])) {
    2. return Array.prototype.concat.apply([], children)
    3. }

    }
    return children
    }

    // 2. When the children contains constructs that always generated nested Arrays,
    // e.g.

发表评论

表情:
评论列表 (有 0 条评论,396人围观)

还没有评论,来说两句吧...

相关阅读