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 功能组件?
基础教程推荐
- 如何添加到目前为止的天数? 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
