vue3 使用css变量

发布于:2025-09-05 ⋅ 阅读:(13) ⋅ 点赞:(0)

虽然 v-bind() 很方便,但当需要处理多个相关联的样式变量时,使用css变量

<template>
  <button class="btn" :style="styleVars">点击我</button>
  <button @click="changeColor">改变颜色</button>
</template>

<script setup>
import { ref, computed } from'vue'
// 主色调
const themeColor = ref('#409EFF')
// 根据主题色计算阴影颜色
const shadowColor = computed(() => {
    // 简单示例:实际应用中可以用更精确的颜色计算
    return`${themeColor.value}40`// 添加透明度})
    // // 集中管理所有样式变量
})
const styleVars = computed(() => 
    ({'--btn-bg': themeColor.value,'--btn-text-color': '#fff','--btn-shadow': `0 4px 10px ${shadowColor.value}`})
 )

 const changeColor = () => {
    themeColor.value = themeColor.value === '#409EFF' ? '#f56c6c' : '#409EFF'
}

</script>

<style scoped>
/* :root{
    --btn-bg: red;
    --btn-text-color: #fff;
    --btn-shadow: 0 4px 10px rgba(64, 158, 255, 0.4);
} */
.btn {
  background-color: var(--btn-bg);
  color: var(--btn-text-color);
  box-shadow: var(--btn-shadow);
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.btn:hover {
  opacity: 0.9;
}
</style>

Vue 3 提供了 v-bind() 函数,让我们可以直接在 CSS 中使用 JavaScript 变量:

<template>
<p>示例文字</p>
</template>

<scriptsetup>
import { ref } from'vue'
const textColor = ref('red')
</script>

<stylescoped>
p {
color: v-bind('textColor');
}
</style>

缺点:用完 v-bind('响应式变量后') 会在每一个元素加这个键名,而自定义的变量不会

CSS 变量的命名规则如下:

  1. 必须以两个连字符开头:--

    • 例如:--main-color--font-size
  2. 只能包含字母、数字、连字符(-)和下划线(_),不能包含空格或其他特殊字符。

  3. 区分大小写,但建议全部小写,便于统一管理。

  4. 命名建议有语义,体现用途或作用,例如:

    • --primary-bg
    • --header-height
    • --button-radius
  5. 可以使用驼峰或连字符风格,但推荐连字符风格(如 --main-color

<template>
  <button class="btn" :style="styleVars">点击我</button>
  <button @click="changeColor">改变颜色</button>
  <p class="text">示例文字</p>
</template>

<script setup>
import { ref, computed } from'vue'
// 主色调
const themeColor = ref('#409EFF')
const textColor = ref('red')
// 根据主题色计算阴影颜色
const shadowColor = computed(() => {
    // 简单示例:实际应用中可以用更精确的颜色计算
    return`${themeColor.value}40`// 添加透明度})
    // // 集中管理所有样式变量
})
const styleVars = computed(() => 
    ({'--btn-bg': themeColor.value,'--btn-text-color': '#fff','--btn-shadow': `0 4px 10px ${shadowColor.value}`})
 )

 const changeColor = () => {
    themeColor.value = themeColor.value === '#409EFF' ? '#f56c6c' : '#409EFF';
    textColor.value = textColor.value === 'red' ? 'blue' : 'red';
}

</script>

<style scoped>
/* :root{
    --btn-bg: red;
    --btn-text-color: #fff;
    --btn-shadow: 0 4px 10px rgba(64, 158, 255, 0.4);
} */
.btn {
  background-color: var(--btn-bg);
  color: var(--btn-text-color);
  box-shadow: var(--btn-shadow);
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.btn:hover {
  opacity: 0.9;
}

.text{
    color: v-bind('textColor')
}
</style>


网站公告

今日签到

点亮在社区的每一天
去签到