Функции рендеринга (render functions) в Vue предоставляют более гибкую альтернативу шаблонам. Рассмотрим эквиваленты основных шаблонных конструкций в render-функциях.
Шаблон:
<div v-if="condition">Content</div>
<div v-else>Alternative</div>
Render-функция:
render(h) {
return this.condition
? h('div', 'Content')
: h('div', 'Alternative')
}
Шаблон:
<ul>
<li v-for="item in items" :key="item.id">{{ item.text }}</li>
</ul>
Render-функция:
render(h) {
return h('ul',
this.items.map(item =>
h('li', { key: item.id }, item.text)
)
}
Шаблон:
<input v-model="message">
Render-функция:
render(h) {
return h('input', {
domProps: { value: this.message },
on: {
input: e => { this.message = e.target.value }
}
})
}
Шаблон:
<child-component>
<template v-slot:default>Default Slot</template>
<template v-slot:named>Named Slot</template>
</child-component>
Render-функция:
render(h) {
return h('child-component', {
scopedSlots: {
default: () => 'Default Slot',
named: () => 'Named Slot'
}
})
}
Шаблон:
<div :class="dynamicClass" :style="dynamicStyle"></div>
Render-функция:
render(h) {
return h('div', {
class: this.dynamicClass,
style: this.dynamicStyle
})
}
Шаблон:
<button @click="handleClick">Click</button>
Render-функция:
render(h) {
return h('button', {
on: {
click: this.handleClick
}
}, 'Click')
}
Шаблон:
<component :is="currentComponent" />
Render-функция:
render(h) {
return h(this.currentComponent)
}
Шаблон:
<input @keyup.enter="submit">
Render-функция:
render(h) {
return h('input', {
on: {
keyup: e => {
if (e.key === 'Enter') this.submit()
}
}
})
}
Шаблон:
<div v-custom-directive:arg.modifier="value"></div>
Render-функция:
render(h) {
return h('div', {
directives: [{
name: 'custom-directive',
value: this.value,
arg: 'arg',
modifiers: { modifier: true }
}]
})
}
Шаблон:
<template functional>
<div>{{ props.message }}</div>
</template>
Render-функция:
Vue.component('functional-comp', {
functional: true,
render(h, { props }) {
return h('div', props.message)
}
})
Шаблон:
<div class="container">
<h1 v-if="title">{{ title }}</h1>
<ul>
<li v-for="item in items" @click="selectItem(item)">
{{ item.name }}
</li>
</ul>
</div>
Эквивалентная render-функция:
render(h) {
const children = []
if (this.title) {
children.push(h('h1', this.title))
}
const listItems = this.items.map(item =>
h('li', {
on: {
click: () => this.selectItem(item)
}
}, item.name)
)
children.push(h('ul', listItems))
return h('div', { class: 'container' }, children)
}
render-функции предоставляют полный эквивалент шаблонных возможностей Vue, но с более явным и гибким синтаксисом. Понимание этих соответствий критически важно для работы с динамическими компонентами, JSX и сложными сценариями рендеринга.