什么是CSS变量
本文已经假设你熟悉CSS变量,如果不熟悉,可以看我写的CSS变量基础知识:https://www.jianshu.com/p/a0f6233cf335
在研究Vue 3的“单文件驱动的CSS变量”之前,我们先看看Vue 2怎么使用CSS变量。
Vue 2由js向css传递变量的方式
-
<template>的顶层容器:给顶层容器设一个style:
:style="cssVars"
,用于向下层元素传递变量。 -
下层元素:我随意设2个下层元素:
<div class="a-container">A元素</div>
<div class="b-container">B元素</div>
- data和computed:要写一个计算属性用于返回
cssVars
。
data() {
return {
xxHeight: 33,
ooColor: 'red',
};
},
computed: {
cssVars() {
return {
'--xx-height': this.xxHeight + 'px',
'--oo-color': this.ooColor,
}
}
},
- <style>:设上样式:
<style lang="scss">
.a-container {
height: var(--xx-height);
}
.b-container {
color: var(--oo-color);
}
</style>
- 效果:A元素的高度就会是33px,B元素是红色。当data有变化,则两个元素会立即变化。
CSS变量跟<div :style="{height: xxHeight}"></div>方式比,有什么优势?
:style是行内样式,行内样式的缺点至少有三个:1. 字符多,写起来麻烦;2. 行内意味着无法复用,class可以复用;3. :style无法定义伪元素的样式。
CSS变量优势其实很明显,上面案例中,<div class="a-container">A元素</div>
并没有写style,而且,a-container
是可以复用的,可以用在无数个元素上。最后,在<style>标签里可以定义伪元素的样式。
Vue 3“单文件驱动的CSS变量”是怎么回事
基本用法
Vue 3加入了“单文件驱动的CSS变量”,它也是一种语法糖,到今天有2个版本,旧版简称“style vars”版本,因为被人诟病“创造了方言”而改成了新版,旧版我就不说了,新版用法举例:
<template>
<div>
<div class="a">A</div><div class="b">B</div>
</div>
</template>
<script setup>
ref: xxHeight = 33;
ref: ooColor = 'red';
</script>
<style>
.a {
height: v-bind(xxHeight + 'px');
}
.b {
color: v-bind(ooColor);
}
</style>
也就是说,凡是<style>中使用了v-bind函数,都将传值视为CSS变量表达式,而且缺省--
符号。变量会自动去<script setup>里查找同名顶层变量。
如果需要拼接字符串怎么办?
拼接字符串要遵循CSS变量规范,CSS变量规范并没有直接拼接字符串的办法,而是采用calc乘法。
<template>
<div>
<div class="a">A</div>
</div>
</template>
<script setup>
ref: xxHeight = 33;
</script>
<style>
.a {
height: calc(v-bind(xxHeight) * 1px);
}
</style>
如果需要获取对象属性怎么写?
写起来是对象的点运算符,但是要用引号包裹起来,而且为了跟CSS常用的双引号区分,最好使用单引号。
<template>
<div>
<div class="b">B</div>
</div>
</template>
<script setup>
import { reactive } from 'vue';
let ooColor = reactive({w: 'red'});
</script>
<style>
.b {
color: v-bind('ooColor.w');
}
</style>
Vue 3跟2的区别是什么?
Vue 2的写法在3里依然可用,而且更贴近原生,可以说是标准写法,而Vue 3实际上是2的语法糖。
方便程度上说,Vue 3的肯定更方便。
浏览器兼容性
由于使用CSS变量,所以IE全不支持,老内核Edge全不支持。
网友评论