本文介绍了如何从父组件向Vue.js功能组件应用类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个功能组件:

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>

结果 DOM 没有 new-class 应用于Functional子组件。据我所知, Vue-loader 针对渲染功能组件渲染函数 context 。这意味着不会直接应用类并智能地合并。

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.

问题是 - 如何使用外部应用类使功能组件很好地发挥作用模板?

注意:我知道很容易通过渲染功能这样做:

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


推荐答案

没有渲染功能的方法是:

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绑定所有其他东西,你可能不需要它,但它会绑定像 ID 。你不能在课堂上使用它,因为那是一个保留的js对象,所以vue使用 staticClass ,所以必须使用手动完成绑定: class =data.staticClass,并且由于该类可能未由父级定义,因此您应该使用:class =data.staticClass ||''

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 || ''"

我无法将其显示为小提琴,因为只有功能组件定义为* .vue文件中的单个文件组件也收到适当的模板编译

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

这篇关于如何从父组件向Vue.js功能组件应用类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 06:10