前言
最近项目演示,手上没什么活,正好借着闲下来的功夫,看了看 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 变量的麻烦。
评论