How to apply classes to Vue.js Functional Componen

2019-05-11 13:01发布

Suppose I have a functional component:

<template functional>
    <div>Some functional component</div>
</template>

Now I render this component in some parent with classes:

<parent>
    <some-child class="new-class"></some-child>
</parent>

Resultant DOM doesn't have new-class applied to the Functional child component. Now as I understand, Vue-loader compiles Functional component against render function context as explained here. That means classes won't be directly applied and merge intelligently.

Question is - how can I make Functional component play nicely with the externally applied class when using a template?

Note: I know it is easily possible to do so via render function:

Vue.component("functional-comp", {
    functional: true,
    render(h, context) {
        return h("div", context.data, "Some functional component");
    }
});

2条回答
相关推荐>>
2楼-- · 2019-05-11 13:25
闹够了就滚
3楼-- · 2019-05-11 13:28

The way you could do it without a render function is:

<template functional>
  <div class="my-class" :class="data.staticClass || ''" v-bind="data.attrs">
    //...
  </div>
</template>

v-bind binds all the other stuff, you may not need it, but it will bind things like id. you can't use it for class though, because that's a reserved js object so vue uses staticClass, so that binding has to be done manually using :class="data.staticClass", and in since the class may not defined by parent, you should use :class="data.staticClass || ''"

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

查看更多
登录 后发表回答