谁能帮助我理解如何控制组件根元素css类的顺序,以及从调用组件的父类绑定的任何css类的顺序?
下面是一个小提琴,它描述了我所注意到的(下面的代码片段示例):https://jsfiddle.net/cicsolutions/b6rnaw25/
您会注意到,如果有一个组件的根元素上有一个类,如果该类是一个字符串,则Vue的类绑定会将该类放在结果绑定类列表的开头。这是我所期望的,因为组件设置了基本的css类,然后您可以在使用组件时通过向组件html元素添加类来自定义样式。然后,Vue将这些类绑定/连接在一起。
在接下来的小提琴示例中,我将展示如何使用动态的css类(即不是静态字符串)。在这些情况下,Vue将组件的根元素类放在绑定类列表的末尾。
我正在开发一个组件,希望其他人也能使用,所以我想在根元素上设置我的组件类,然后如果有人想要覆盖这些样式,他们可以在组件标记上添加自己的类。
我还需要根元素类是动态的,因此必须使用数组或对象来处理类绑定。
有人知道为什么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>
发布于 2019-03-06 10:07:18
我怀疑Vue首先插入静态类并没有什么特别的原因;可能它只是反映了renderClass函数中输入参数的顺序。
此外,CSS文件中规则集的顺序也很重要;元素的class属性中的类名顺序并不重要。而且这两个顺序都与cascade无关,它指代从父元素继承样式的子元素。也许您把它与块或内联样式中声明的顺序搞混了。在这种情况下,顺序确实很重要:
<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>https://stackoverflow.com/questions/55013391
复制相似问题