Skip to content

Commit 6040967

Browse files
chrisvfritzyyx990803
authored andcommitted
add section about using plain javascript in render functions to replace some template features
1 parent 2dd5cc1 commit 6040967

File tree

1 file changed

+30
-4
lines changed

1 file changed

+30
-4
lines changed

src/guide/render-function.md

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ createElement(
112112
// HTML tag name, you can just use an array of
113113
// VNodes directly. Optional.
114114
[
115-
createElement('h1', ['hello world'])
115+
createElement('h1', 'hello world')
116116
createElement(MyComponent, {
117117
props: {
118118
someProp: 'foo'
@@ -209,6 +209,33 @@ Vue.component('anchored-heading', {
209209
})
210210
```
211211

212+
## Replacing Template Features with Plain JavaScript
213+
214+
Wherever something can be easily accomplished in plain JavaScript, Vue render functions do not provide a propriety alternative. For example, in a template using `v-if` and `v-for`:
215+
216+
``` html
217+
<div>
218+
<ul v-if="items.length">
219+
<li v-for="item in items">{{ item.name }}</li>
220+
</ul>
221+
<p v-else>No items found.</p>
222+
</div>
223+
```
224+
225+
This could be rewritten with JavaScript's `if-else` and `map` in a render function:
226+
227+
``` js
228+
render: function (createElement) {
229+
if (this.items.length) {
230+
return createElement('ul', this.items.map(function (item) {
231+
return createElement('li', item.name)
232+
}))
233+
} else {
234+
return createElement('p', 'No items found.')
235+
}
236+
}
237+
```
238+
212239
## Rendering Components with Children
213240

214241
As mentioned above, components with children must use a thunk: i.e. a function that returns an array of children, rather than the array of children directly. This delays children creation until the component itself is rendered, allowing more efficient re-renders.
@@ -220,16 +247,15 @@ new Vue({
220247
el: '#demo',
221248
render: function (createElement) {
222249
return createElement(
223-
Vue.options.components['anchored-heading'],
224-
{
250+
Vue.options.components['anchored-heading'], {
225251
props: {
226252
level: 1
227253
}
228254
},
229255
// Here's the "thunk"
230256
function () {
231257
return [
232-
createElement('span', 'Hello'),
258+
createElement('strong', 'Hello'),
233259
' world!'
234260
]
235261
}

0 commit comments

Comments
 (0)