CIC*_*ons 5 javascript css vue.js
谁能帮助我了解如何控制组件根元素 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
}
}
})Run Code Online (Sandbox Code Playgroud)
body {
background: #20262E;
padding: 20px;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
}
h2 {
margin-bottom: 0.75rem;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
我怀疑 Vue 首先插入静态类没有什么特别的原因;可能它只是镜像函数中输入参数的顺序renderClass。
CSS 文件中规则集的顺序也很重要;class元素属性中类名的顺序不同。这两个顺序都与cascade没有任何关系,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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2257 次 |
| 最近记录: |