渲染函数基础
渲染函数是 Vue 提供的一种编程式创建虚拟 DOM 的方式,适用于需要完全控制组件输出或动态生成内容的场景。
什么是渲染函数
模板语法(template)适用于大多数场景,但当需要完整的 JavaScript 编程能力时,渲染函数提供了更底层的控制。
渲染函数接收 createElement(简称 h)作为参数,返回一个虚拟 DOM 节点(VNode)。
JavaScript
Vue.component('heading', {
render(h) {
return h('h1', {}, '标题内容')
}
})
渲染函数最终返回的是虚拟 DOM 对象,Vue 的 Diff 算法会将其与旧 VNode 对比并更新真实 DOM。
基础语法
JavaScript
new Vue({
el: '#app',
render(h) {
return h(
'div', // 标签名或组件
{ /* 数据对象 */ }, // 属性、样式、事件等
[ /* 子节点数组 */ ] // 子 VNode 或文本
)
}
})
参数说明
| 参数 | 类型 | 说明 |
|---|---|---|
| 第一个参数 | String/Function/Object | HTML 标签名、组件或异步组件 |
| 第二个参数 | Object(可选) | 数据对象,包含属性、样式、类等 |
| 第三个参数 | Array/String(可选) | 子节点,可以是文本字符串或 VNode 数组 |
使用场景
动态标签级别
vue
<template>
<!-- 使用模板需要多个 if-else -->
<h1 v-if="level === 1"><slot /></h1>
<h2 v-else-if="level === 2"><slot /></h2>
<h3 v-else-if="level === 3"><slot /></h3>
</template>
JavaScript
// 使用渲染函数更简洁
Vue.component('dynamic-heading', {
props: {
level: { type: Number, required: true }
},
render(h) {
return h(
`h${this.level}`, // 动态标签名
this.$slots.default // 插槽内容
)
}
})
条件渲染
JavaScript
render(h) {
if (this.items.length) {
return h('ul', this.items.map(item => h('li', item.name)))
}
return h('p', '暂无数据')
}
数据对象
第二个参数是数据对象,包含属性、样式、类、事件等配置。
JavaScript
render(h) {
return h('div', {
// 与 v-bind:class 相同
class: {
'active': this.isActive,
'container': true
},
// 与 v-bind:style 相同
style: {
color: 'red',
fontSize: '14px'
},
// 普通 HTML 属性
attrs: {
id: 'main',
'data-custom': 'value'
},
// DOM 属性
domProps: {
innerHTML: '<b>粗体内容</b>'
},
// 事件监听
on: {
click: this.handleClick
},
// 原生事件
nativeOn: {
click: this.handleClick
},
// 指令
directives: [
{
name: 'my-custom-directive',
value: '指令值',
expression: 'string',
arg: 'foo',
modifiers: { bar: true }
}
],
// 插槽
slot: 'default',
// 组件 props
props: {
myProp: 'value'
}
}, '内容')
}
插槽内容
渲染函数中可通过 this.$slots 和 this.$scopedSlots 访问插槽内容。
JavaScript
render(h) {
// 默认插槽
const defaultSlot = this.$slots.default
// 具名插槽
const headerSlot = this.$slots.header
// 作用域插槽
const scopedSlot = this.$scopedSlots.item({ text: '传入数据' })
return h('div', [
headerSlot,
h('main', defaultSlot),
scopedSlot
])
}
v-model 实现
渲染函数中需要手动实现 v-model:
JavaScript
render(h) {
const self = this
return h('input', {
domProps: {
value: self.value
},
on: {
input(event) {
self.$emit('input', event.target.value)
}
}
})
}
要点总结
- 渲染函数通过
h()编程式创建虚拟 DOM,返回 VNode 对象 - 三个参数:标签名/组件、数据对象(可选)、子节点(可选)
- 适用于动态生成内容、条件渲染、复用逻辑等场景
- 数据对象包含
class、style、attrs、on、directives等配置 - 插槽通过
this.$slots和this.$scopedSlots访问 v-model需手动实现为valueprop +input事件
存放路径:articles/VUE/进阶/自定义指令与渲染函数/渲染函数基础.md
📝 发现内容有误?点击此处直接编辑