Data objects

The second optional argument is the data object, which allows you to pass additional information about the element to createElement (or h). For example, you can specify CSS classes in the same way we use the v-bind:class directive in our classic templates, or we can add event listeners.

Here is an example of a data object that covers most features:

{
// Same API as `v-bind:class`
'class': {
foo: true,
bar: false
},
// Same API as `v-bind:style`
style: {
color: 'red',
fontSize: '14px'
},
// Normal HTML attributes
attrs: {
id: 'foo'
},
// Component props
props: {
myProp: 'bar'
},
// DOM properties
domProps: {
innerHTML: 'baz'
},
// Event handlers are nested under "on", though
// modifiers such as in v-on:keyup.enter are not
// supported. You'll have to manually check the
// keyCode in the handler instead.
on: {
click: this.clickHandler
},
// For components only. Allows you to listen to
// native events, rather than events emitted from
// the component using vm.$emit.
nativeOn: {
click: this.nativeClickHandler
},
// Custom directives. Note that the binding's
// oldValue cannot be set, as Vue keeps track
// of it for you.
directives: [
{
name: 'my-custom-directive',
value: '2'
expression: '1 + 1',
arg: 'foo',
modifiers: {
bar: true
}
}
],
// The name of the slot, if this component is the
// child of another component
slot: 'name-of-slot'
// Other special top-level properties
key: 'myKey',
ref: 'myRef'
}

For example, we can apply a special CSS class if the title level is below a specific number:

Vue.component('my-title', {
props: ['level'],
render (h) {
return h(
// Tag name
`h${this.level}`,
// Data object
{
'class': {
'important-title': this.level <= 3,
},
},
// Default slot content
this.$slots.default,
)
}
})

We could also put a click event listener that calls a method of the component:

Vue.component('my-title', {
props: ['level'],
render (h) {
return h(
// Tag name
`h${this.level}`,
// Data object
{
on: {
click: this.clickHandler,
},
},
// Default slot content
this.$slots.default,
)
},
methods: {
clickHandler (event) {
console.log('You clicked')
},
},
})

You can find the full description of this object in the official documentation (https://vuejs.org/v2/guide/render-function.html#The-Data-Object-In-Depth).

As we have seen, Vue uses render functions in pure JavaScript under-the-hood of our templates! We can even write our own render functions, using the createElement (or h) function to construct the elements to be added to the Virtual-DOM.

This way of writing our views is more flexible and powerful than templates, but is more complex and verbose. Use it when you feel comfortable with it!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.168.172