How to apply classes to Vue.js Functional Component from parent component?(如何将类从父组件应用到 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>
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 绑定所有其他的东西,你可能不需要它,但它会绑定像 id 或 style 这样的属性.问题是你不能将它用于 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
这篇关于如何将类从父组件应用到 Vue.js 功能组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将类从父组件应用到 Vue.js 功能组件?
- 从原点悬停时触发 translateY() 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
