如何从父组件将类应用到 Vue.js 功能组件? [英] How to apply classes to Vue.js Functional Component from parent component?
问题描述
假设我有一个功能组件:
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
将 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
绑定所有其他的东西,你可能不需要它,但它会绑定像 id
或 style
这样的属性.问题是你不能将它用于 class
因为它是一个保留的 js 对象所以 vue 使用 staticClass
,所以必须使用 :class 手动完成绑定="data.staticClass"
.
This will fail if the staticClass
property is not defined, by the parent, so you should use :class="data.staticClass || ''"
如果 staticClass
属性没有被父级定义,这将失败,所以你应该使用 :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
这篇关于如何从父组件将类应用到 Vue.js 功能组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!