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>


相关推荐
wd5i8kA8i17 小时前
自研多线程 SSH 极速文件传输助手(附 GitHub 源码)
运维·ssh·github
Boop_wu18 小时前
[Java 算法] 字符串
linux·运维·服务器·数据结构·算法·leetcode
m0_6948455718 小时前
Dify部署教程:从AI原型到生产系统的一站式方案
服务器·人工智能·python·数据分析·开源
菱玖19 小时前
SRC常见漏洞情况分类
运维·安全·安全威胁分析
码云数智-大飞19 小时前
C++ RAII机制:资源管理的“自动化”哲学
java·服务器·php
SkyXZ~19 小时前
Jetson有Jtop,Linux有Htop,RDK也有Dtop!
linux·运维·服务器·rdkx5·rdks100·dtop
黑牛儿20 小时前
MySQL 索引实战详解:从创建到优化,彻底解决查询慢问题
服务器·数据库·后端·mysql
舒一笑20 小时前
一次“翻车”的部署,让我看清了技术、权力和职场的真相
运维·程序员·创业
starvapour20 小时前
Ubuntu系统下基于终端的音频相关命令
linux·ubuntu·音视频
杨云龙UP21 小时前
Oracle Data Pump实战:expdp/impdp常用参数与导入导出命令整理_20260406
linux·运维·服务器·数据库·oracle