优良作法是在根元素上放置一个标识组件的类,以简化从外部(和内部)进行的样式设计。
肯定可以手动将其添加到模板中(或在渲染器中使用staticClass
选项),但是我认为将其添加为全局mixin并使该约定成为自动默认值(使该组件保持kebab大小)非常有用。命名并将其添加为静态类。
我制作了这个mixin,它试图使其与未记录的$vnode
和staticClass
API配合使用(使用$el.classList.addClass
无效,因为Vue将其用于动态类绑定,从而删除了可以通过直接访问将其放置在那里),但是更新后的静态类仅添加到某些组件上,我不知道如何进一步对其进行调试。
有适当知识的人可以帮助我吗?
import Vue from 'vue';
import { kebabCase, isEmpty, isUndefined, set, get } from 'lodash-es';
/**
* Simple helper to check whether a variable is defined.
* It's implemented as a type guard to make TypeScript infer when the undefined part is removed.
*/
function isDefined<T = any>(value: T): value is Exclude<T, undefined> {
return !isUndefined(value);
}
export const ApplyComponentNameAsClass = Vue.extend({
mounted() {
if (
isEmpty(this.$options.name) ||
this.$el.nodeType !== Node.ELEMENT_NODE
) {
return;
}
const componentNameStaticClass = kebabCase(this.$options.name);
const currentStaticClass: string | undefined = get(this.$vnode, 'data.staticClass');
const staticClasses = [componentNameStaticClass, currentStaticClass].filter(isDefined);
set(this.$vnode, 'data.staticClass', staticClasses.join(' '));
// Component wouldn't be re-rendered otherwise,
// and the newly added class wouldn't be added
// until next rendering update
this.$forceUpdate();
}
});