繁体   English   中英

了解Vue.js CSS类绑定顺序

[英]Understanding Vue.js CSS Class Binding Ordering

谁能帮助我了解如何控制组件根元素css类以及可能与调用该组件的父对象绑定的任何css类的顺序?

这是描述我所注意的小提琴(下面的片段示例): https : //jsfiddle.net/cicsolutions/b6rnaw25/

您会注意到,如果您的组件的根元素上有一个类,如果该类是字符串,则Vue的类绑定会将类放在结果绑定的类列表的开头。 这是我所期望的,因为组件设置了基本的CSS类,然后在使用组件时可以通过将类添加到组件html元素中来自定义样式。 然后,Vue将这些类绑定/合并在一起。

在小提琴中的下一个示例中,我展示了动态css类的使用(即,不是静态字符串)。 在这些情况下,Vue将组件的根元素类放在绑定的类列表的末尾。

我正在开发一个希望其他人使用的组件,所以我想将我的组件类设置在root元素上,然后,如果有人想覆盖这些样式,他们可以在自己的组件标签上添加自己的类。

我还需要根元素类是动态的,因此我必须使用数组或对象来处理类绑定。

有谁知道为什么Vue在静态类的开头和动态类的末尾放置组件根css类? 这对我来说似乎很奇怪,但是也许出于某种原因是故意的。

但是,当我需要将其作为动态类时,如何确保组件的根元素类始终在结果绑定类列表中排在首位?

 Vue.directive('bound-class', (el) => { const boundClass = el.attributes.class.nodeValue const boundClassPrintout = document.createElement('div') boundClassPrintout.innerHTML = 'Resulting Bound Class: ' + boundClass el.appendChild(boundClassPrintout) }); // STATIC CSS CLASS -> becomes 1st class in bound class list (expected) Vue.component('string-test', { template: `<div class="string-class" v-bound-class><slot></slot></div>` }); // DYNAMIC CSS CLASS -> becomes last class in bound class list (unexpected) Vue.component('array-test', { template: `<div :class="['array-class']" v-bound-class><slot></slot></div>` }); // DYNAMIC CSS CLASS -> becomes last class in bound class list (unexpected) Vue.component('object-test', { template: `<div :class="{ 'object-class': true }" v-bound-class><slot></slot></div>` }); new Vue({ el: "#app", computed: { vueVersion() { return Vue.version } } }) 
 body { background: #20262E; padding: 20px; } #app { background: #fff; border-radius: 4px; padding: 20px; } h2 { margin-bottom: 0.75rem; } 
 <link href="https://cdn.jsdelivr.net/npm/tailwindcss/dist/tailwind.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <h2>Vue version: {{ vueVersion }}</h2> <string-test class="p-2 mb-2 border">Root class (string-class) at beginning (expected)</string-test> <array-test class="p-2 mb-2 border">Root class (array-class) at end (unexpected)</array-test> <object-test class="p-2 mb-2 border">Root class (object-class) at end (unexpected)</object-test> </div> 

我怀疑Vue首先插入静态类没有特别的原因。 可能只是镜像renderClass函数中输入参数的renderClass

CSS文件中规则集的顺序也很重要。 类名称在元素的class属性中的顺序不正确。 而且这两个顺序都与级联无关, 级联是指子元素从其父级继承样式。 也许您已经将其与块内或内联样式中的声明顺序混淆了。 在这种情况下,顺序很重要:

<p class="red blue">
    Order doesn't matter in the class attribute above. If
    the class styles contradict, whichever is defined last
    will win regardless of how they're ordered in the attribute.
</p>

<p class="blue red">
    This paragraph will be styled identically to the previous
    one, despite the change in class order.
</p>

<p style="color: red; color: blue">
    Order does matter here. The text color will be blue.
</p>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM