vue h函数中创建虚拟节点

147 阅读2分钟

在Vue开发中,h函数堪称构建虚拟DOM的得力助手。它能高效创建虚拟节点,为组件渲染奠定基础。在涉及Element Plus的el - tag组件渲染时,h函数更是发挥着关键作用。

当使用h函数创建el - tag组件时,务必留意正确的使用方式。例如,切勿直接将'el - tag'字符串作为h函数的首个参数,像h('el - tag', { type: color }, text)这样的写法,Vue会误将其当作普通HTML标签处理,导致样式不生效或渲染异常。正确做法是先导入Element Plus的el - tag组件,即import { ElTag } from 'element - plus';,随后在创建组件处使用h(ElTag, { type: color }, text),如此Vue便能精准识别并渲染出具备完整样式与功能的el - tag组件。

    // 自定义内容
    getCustomRender(column) {
      // 自定义列内容
      if (column.fieldCode === 'isSystem') {
        return (row) => {
          const text = row[column.fieldCode] === 1 ? '是' : '否';
          const color = row[column.fieldCode] === 1 ? 'success' : 'danger';
          return h(ElTag, { type: color }, text); // 使用 h 函数创建 el-tag 组件
        };
      }
      return null;
    }
    
    // 传入组件
   <TableColumnRenderer
          v-for="column in configColumns"
          :key="column.fieldId"
          :custom-render="getCustomRender(column)"
  />

在实际项目中,以TableColumnRenderer组件为例,我们可借助h函数实现自定义渲染逻辑。在父组件中,通过导入el - tag组件并定义getCustomRender函数,依据列配置判断是否进行自定义渲染。若列的fieldCodeisSystem,便使用h函数创建el - tag组件,依据数据决定标签类型与显示文本。这种方式使得h函数在构建复杂且灵活的组件渲染逻辑中展现出强大功能,助力开发者轻松应对多样化的项目需求。

伪代码如下:

<template>
    <template #default="{ row }">
      <!-- 如果有自定义渲染函数,使用自定义渲染 -->
      <template v-if="customRender">
        <component :is="customRender(row)" />
      </template>
    </template>
</template>

<script>
export default {
  props: {
    customRender: {
      type: Function,
      default: null
    }
  }
}
</script>