Vue3中样式变量的使用

css 复制代码
//'./assets/styles/variables.module.scss'

$headerHeight: 140px;
$footerHeight: 200px;

:export {
  headerHeight: $headerHeight;
  footerHeight: $footerHeight;
}

:root {
  --headerHeight: #{$headerHeight};
  --footerHeight: #{$footerHeight};
  --customProperty: 我是自定义属性在 root 中定义;
}
javascript 复制代码
import { createApp } from 'vue'

import './assets/styles/variables.module.scss'

import App from './App.vue'

createApp(App).mount('#app')
javascript 复制代码
<script setup>
import {computed, ref} from "vue";
import variables from '@/assets/styles/variables.module.scss'

//场景1 通过xxx.module.scss定义样式变量 js中通过variables.xxx获取
console.log('🍎', variables, 'headerHeight=' + variables?.headerHeight);

//场景2 通过getComputedStyle(DOMElement).getPropertyValue方法获取:root下定义的样式变量
console.log('🍊', getComputedStyle(document.documentElement)
.getPropertyValue('--customProperty')
);

const isWhite = ref(true);

const getFontColor = computed(() => {
  return isWhite.value ? 'white' : 'black'
})

const changeFontColor = () => {
  isWhite.value = !isWhite.value
}
</script>

<template>
  <div class="test-style">
    Hello world!
  </div>
  <button @click="changeFontColor">change Font Color</button>
</template>

<style scoped lang="sass">
.test-style
  //场景3 在style标签中获取root中定义的变量
  height: calc(50svh - var(--headerHeight))
  //场景4 通过v-bind结合vue的computed函数动态获取(常用于dark/light切换场景)
  color: v-bind(getFontColor)
  display: flex
  justify-content: center
  align-items: center
  font-size: 200px
  font-weight: bold
  background-color: #a2dc04
  text-shadow: #fff7f4 -8px 0px 5px
</style>


相关推荐
mN9B2uk1725 分钟前
大数据量高并发的数据库优化
服务器·数据库·oracle
starvapour27 分钟前
Ubuntu部署gitlab频繁出现502的问题
linux·ubuntu·gitlab
jinglong.zha33 分钟前
LScript-从零基础到商业变现的AI自动化学习平台
运维·学习·自动化
土星云SaturnCloud35 分钟前
边缘计算赋能智慧工地:从“看得见“到“管得住“的智能化升级
服务器·人工智能·ai·边缘计算
Adorable老犀牛1 小时前
Telegraf:InfluxData 出品的指标采集代理
运维·telegraf
北塔软件1 小时前
北塔软件智能体平台 | 不只监控,更是AI时代的数据资产
运维·人工智能·知识库·北塔软件
zhangfeng11331 小时前
ps aux讲解,结合国家超算中心 hpc apptainer
linux·服务器·网络
夜月yeyue1 小时前
STM32 DMA 双缓冲采样
linux·stm32·单片机·嵌入式硬件·系统架构
ScilogyHunter1 小时前
Buildroot完全指南:从入门到实战
linux·嵌入式·buildroot
毕竟是shy哥2 小时前
Claude Code 接入 DeepSeek 保姆级教程,WSL/Linux 通用
linux·安装教程·codex·deepseek·claude code·openclaw