vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vue3渲染器与渲染函数

Vue3渲染器与渲染函数的用法详解

作者:编程随想_Code

Vue3渲染器将虚拟DOM转为真实DOM,支持高效更新与跨平台;渲染函数(h())替代JSX,更灵活,与CompositionAPI结合可优化性能,提升复杂场景下的开发效率与应用性能

一、渲染器:虚拟DOM的操作核心

渲染器是 Vue 内部的核心模块,负责将虚拟 DOM (VNode) 转换为真实 DOM。

Vue3 的渲染器具有以下特点:

渲染器关键功能:

二、渲染函数:JSX 的替代方案

Vue3 提供了 h() 函数(hyperscript)作为创建 VNode 的主要方式:

import { h } from 'vue'

export default {
  render() {
    return h(
      'div', 
      { class: 'container', id: 'app' },
      [
        h('h1', { style: { color: 'blue' } }, '标题'),
        this.showSubtitle ? 
          h('p', null, '动态子标题') : 
          h('div', { class: 'placeholder' }),
        h('ul', null, 
          this.items.map(item => 
            h('li', { key: item.id }, item.text)
          )
        )
      ]
    )
  }
}

三、渲染函数 vs JSX

特性渲染函数JSX
语法纯 JavaScript 函数调用XML-like 语法扩展
类型支持需要额外类型定义完美支持 TypeScript
动态内容需要手动条件判断支持内联表达式
组件引用直接使用组件变量需要导入组件
学习曲线较低(纯JS)较高(新语法)

四、自定义渲染器实战

Vue3 允许创建自定义渲染器,实现非 DOM 环境渲染:

import { createRenderer } from 'vue'

const { createApp } = createRenderer({
  createElement(type) {
    console.log(`创建元素: ${type}`)
    return { type }
  },
  
  insert(el, parent) {
    console.log(`插入 ${el.type} 到 ${parent.type}`)
  },
  
  patchProp(el, key, prevValue, nextValue) {
    console.log(`更新属性: ${key} = ${nextValue}`)
  }
})

const app = createApp({
  render() {
    return h('div', { id: 'app' }, [
      h('span', { class: 'text' }, '自定义渲染')
    ])
  }
})

app.mount({ type: 'root' })

五、性能优化技巧

避免不必要的重新渲染

import { shallowRef } from 'vue'

const heavyList = shallowRef([...]) // 浅层响应

合理使用 key 属性

h('div', { key: item.id }, item.content)

利用 Fragment 减少包装元素

return h(Fragment, null, [
  h('header', ...),
  h('main', ...),
  h('footer', ...)
])

缓存静态内容

const staticContent = h('div', { class: 'static' }, '不变的内容')

render() {
  return h('div', [
    staticContent,
    // ...动态内容
  ])
}

六、高级应用场景

动态组件工厂:

function createDynamicComponent(type, props) {
  return h(type, {
    ...props,
    onCustomEvent: handleEvent
  })
}

渲染函数与 Composition API 结合:

import { ref, h } from 'vue'

export default {
  setup() {
    const count = ref(0)
    
    return () => h('div', [
      h('button', {
        onClick: () => count.value++
      }, '增加'),
      h('span', `当前计数: ${count.value}`)
    ])
  }
}

七、总结

掌握渲染器与渲染函数的工作原理,能够帮助开发者:

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文