如何将类从父组件应用到 Vue.js 功能组件?

2022-01-25 00:00:00 javascript vue.js vue-component vuejs2

假设我有一个功能组件:

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 没有将 new-class 应用到 Functional 子组件.现在据我了解,Vue-loader 将 Functional 组件针对 render 函数 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");
    }
});

推荐答案

TL;DR;

使用data.staticClass获取类,使用data.attrs

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

解释:

v-bind 绑定所有其他的东西,你可能不需要它,但它会绑定像 idstyle 这样的属性.问题是你不能将它用于 class 因为这是一个保留的 js 对象所以 vue 使用 staticClass,所以必须使用 :class 手动完成绑定="data.staticClass".

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

如果父级未定义 staticClass 属性,这将失败,因此您应该使用 :class="data.staticClass || ''"

This will fail if the staticClass property is not defined, by the parent, so 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"

我有一个工作的代码框:https://codesandbox.io/s/z64lm33vol

I've got a working codesandbox though: https://codesandbox.io/s/z64lm33vol

相关文章