Vue入门指北——css中的js变量

114 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第十天,点击查看活动详情

前言

最近项目演示,手上没什么活,正好借着闲下来的功夫,看了看vue3的文档,发现vue3对vue3的支持加强了。以前总是想着,如果js中的变量能直接,css中使用,那是多么一件美妙的事情啊,而且优雅。而在这次的vue3里面支持这么做了,你可以随意使用js中的变量,只需一个v-bind()指令就可以实现。下面我给大家简单介绍下,在vue2中css是如何使用js变量的,并对比vue3中的使用,你会发现优雅,太优雅了。

vue2中css内的js变量

假如我们有两个按钮,第一个按钮背景改成粉色,第二个按钮文字改成粉色,你可能会这么写:

<script >
...

data() {
  return {
    color: 'pink',
  }
}
...
</script>

<template>
  <div>
    <button :style="{ background: color }">
      彼时彼刻,恰如此时此刻
    </button>
    <button :style="{ color }">
      彼时彼刻,恰如此时此刻
    </button>
  </div>
</template>

但是,这么写的话,动态样式一但多的话,就会显得特别臃肿。这个时候你就可以通过css变量解决这个问题。

<template>
  <div :style="{'--color': color}">
    <button >
      彼时彼刻,恰如此时此刻
    </button>
    <button>
      彼时彼刻,恰如此时此刻
    </button>
  </div>
</template>
<script >
...

data() {
  return {
    color: 'pink',
  }
}
...
</script>
<style scoped>
button:nth-child(1) {
    background: var(--color);
}
button:nth-child(2) {
  color: var(--color)
}
</style>

上面两种方法中,都做到了,根据data内的color变量动态渲染css样式,一个是要在标签内编写样式,一个是要在标签内声明css变量,说实话比较繁琐。下面我们来看下,在vue3中是如何实现的。

vue3中css内的js变量

在vue3中可以说是非常方便了:

<script setup>
import { ref } from 'vue';
const color = ref('pink');
</script>

<template>
  <div>
    <button >
      彼时彼刻,恰如此时此刻
    </button>
    <button>
      彼时彼刻,恰如此时此刻
    </button>
  </div>
</template>

<style scoped>
button:nth-child(1) {
    background: v-bind(color);
}
button:nth-child(2) {
  color: v-bind(color);
}
</style>

vue3中直接通过v-bind指令就可以与js变量绑定上,既解决了标签内编写样式的臃肿的问题,也省去了声明css变量的麻烦。