How to apply classes to Vue.js Functional Component from parent component?
TL;DR;
Use data.staticClass
to get the class, and bind the other attributes using data.attrs
<template functional>
<div class="my-class" :class="data.staticClass || ''" v-bind="data.attrs">
//...
</div>
</template>
Explanation:
v-bind
binds all the other stuff, and you may not need it, but it will bind attributes like id
or style
. The problem is that you can't use it for class
because that's a reserved js object so vue uses staticClass
, so binding has to be done manually using :class="data.staticClass"
.
This will fail if the staticClass
property is not defined, by the parent, so you should use :class="data.staticClass || ''"
Example:
I can't show this as a fiddle, since only "Functional components defined as a Single-File Component in a *.vue file also receives proper template compilation"
I've got a working codesandbox though: https://codesandbox.io/s/z64lm33vol
Render function inside a functional component example, to supplement @Daniel's answer:
render(createElement, { data } {
return createElement(
'div',
{
class: {
...(data.staticClass && {
[data.staticClass]: true,
})
},
attrs: {
...data.attrs,
}
}
)
}
We can use ES6 computed property name in order to set a static class.