当前位置: 首页 > news >正文

在Vue 中如何使用动态样式

在日常开发中随着用户需求的日益多样化,界面设计也日益复杂,如何在保持代码简洁的同时,实现界面的动态变化,是一项不小的挑战。动态样式作为实现界面动态变化的关键技术手段,不仅能够提升用户体验,还能为开发者提供更加丰富的设计空间。

动态样式在Vue中的应用,主要体现在通过数据绑定、计算属性、条件渲染等技术,使得界面元素的样式能够根据数据状态、用户交互等条件实时调整。这不仅能够实现界面的个性化展示,还能根据不同的使用场景提供更为直观、响应式的视觉反馈。

下面将总结几种动态样式常用的方法

动态style

内联样式绑定一个对象,
:style 是一个动态绑定样式的指令,它允许你将样式应用到元素上,并且这些样式可以根据组件的状态或者数据动态变化。

<template>
  <div class="home">
    <button :style="{backgroundColor: backgroundColor[theme]}" @click="changeColor('default')">default</button>
    <button :style="{backgroundColor: backgroundColor[theme]}" @click="changeColor('new')">new</button>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';

let theme = ref('default')
let backgroundColor = reactive({
  default: 'blue',
  new: 'red',
})
function changeColor(val) {
  theme.value = val
}
</script>

<style lang="scss">
.home{
  background-color: #fff;
  width: 80vw;
  height: 50vh;
  display: flex;
  align-items: center;
  justify-content: center;
  button{
   width: 100px;
   margin: 10px;
  }
}
</style>

动态class


<template>
  <div class="home">
    <button :class="theme" @click="changeColor('default')">default</button>
    <button :class="theme" @click="changeColor('new')">new</button>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';

let theme = ref('default')

function changeColor(val) {
  theme.value = val
}
</script>

<style lang="scss">
.home{
  background-color: #fff;
  width: 80vw;
  height: 50vh;
  display: flex;
  align-items: center;
  justify-content: center;
  button{
   width: 100px;
   margin: 10px;
  }
  .default{
    background-color: blue;
  }
  .new{
    background-color: red;
  }
}
</style>

动态class 动态style 效果

scss变量

SCSS变量是指在SCSS(Sass的一种语法)中定义的变量,这些变量可以在整个项目中的任何SCSS文件中使用。这样做的好处是可以在一个地方集中管理项目的样式,便于统一修改和维护。

SCSS变量的优势

  • 一致性:通过全局变量,可以确保整个项目中使用的颜色、字体大小、间距等样式属性保持一致。
  • 可维护性:如果需要修改某个样式属性,只需修改全局变量的值,而不需要在多个文件中逐一修改。
  • 模块化:全局变量有助于将样式代码模块化,使得代码更加清晰和易于管理。

实际使用

.vue文件中 使用 scss变量

style标签中生命$themeColor变量

<template>
  <div class="home">
    <button>按钮</button>
  </div>
</template>

<script setup>
</script>

<style lang="scss">
$themeColor: #2779e4;
.home{
  background-color: #fff;
  width: 80vw;
  height: 50vh;
  button{
    margin: 20vh auto;
    color: #fff;
    background-color: $themeColor;
  }
}
</style>

引入scss 文件使用

在实际开发中往往 会将scss变量的定义统一放在一个公共scss文件里管理,

/scr/common 下创建 index.scss文件

然后 在 style标签中引入scss文件

index.scss

$themeColor: #2779e4;

.vue

<style lang="scss">
@import "@/common/index.scss";
.home{
  background-color: #fff;
  width: 80vw;
  height: 50vh;
  button{
    margin: 20vh auto;
    color: #fff;
    background-color: $themeColor;
  }
}
</style>

实现全局scss变量

考虑到项目在实际开发中,各种组件都需要统一使用样式变量,每个页面引入是不现实的,最佳的解决方案就是,将scss中的变量在全局引入,所有页面都可以访问到.

安装 sass

npm install sass

vite.config.ts文件中 设置css预处理器

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'

const pathResolve = (dir: string): any => {
  return resolve(__dirname, ".", dir)
}

const alias: Record<string, string> = {
  '@': pathResolve("src")
}


// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias
  },
  css: {
    // css预处理器
    preprocessorOptions: {
      scss: {
        // 引入 index.scss 这样就可以在全局中使用 index.scss中预定义的变量了
        // 给导入的路径最后加上; 
        additionalData: '@import "@/common/index.scss";'
      }
    }
  }
})

有了以上配置,无需再单独引用index.scss,style标签中就可以直接使用 $themeColor变量了,

<style lang="scss">
.home{
  background-color: #fff;
  width: 80vw;
  height: 50vh;
  button{
    margin: 20vh auto;
    color: #fff;
    background-color: $themeColor;
  }
}
</style>

动态修改

原理:提前设置好多种皮肤的对应的样式,然后 利用 css 自定义属性选择器和jsdom操作方法 setAttribute 动态修改 自定义属性 来匹配不同的样式

1.全局配置多种皮肤样式
index.scss

$themeColor: #2779e4;

$themes:(
  default: (
    backgroundColor: blue,
  ),
  new: (
    backgroundColor: red,
  )
);

@mixin themeify {
  @each $theme-name, $theme-map in $themes {
    $theme-map: $theme-map !global;
    [data-theme="#{$theme-name}"] & {
      @content;
    }
  }
}

@function themed($key) {
  @return map-get($theme-map, $key);
}


@mixin getBackgroundColor($color) {
  @include themeify {
    background-color: themed($color)!important;
  }
}

@mixin getColor($color) {
  @include themeify {
    background-color: themed($color)!important;
  }
}

2 .vue文件中获取全局皮肤颜色设置对应样式,且提前初始化样式(这一步可以放到 App.vue中 全局出发一次)

<template>
  <div class="home">
    <select v-model="theme">
      <option value="default">default</option>
      <option value="new">new</option>
    </select>
    <button @click="changeTheme">修改主题</button>
  </div>
</template>

<script setup>
import { ref, onBeforeMount } from 'vue';

let theme = ref('default')
function changeTheme() {
  window.document.documentElement.setAttribute( "data-theme", theme.value );
}
onBeforeMount(() => {
  changeTheme(theme.value)
})
</script>

<style lang="scss">
.home{
  background-color: #fff;
  width: 80vw;
  height: 50vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  select{
    width: 100px;
    margin: 10px;
    @include getBackgroundColor("backgroundColor");
  }
  button{
    // background-color: $themeColor;
    @include getBackgroundColor("backgroundColor");
  }
}
</style>

效果

vue3中 scss和js变量互相使用

在 Vue 3 中使用 SCSS 变量 来实现样式的一致性和可重用性是一个很好的做法。Vue 3 与 SCSS可以很好地协同工作,因为 Vue 的数据驱动的模板语法与 SCSS 的变量系统相兼容。

以下是在 scss中使用js变量 v-bind来实现


<template>
  <div class="home">
    <button class="btn" @click="changeColor('blue')">default</button>
    <button class="btn" @click="changeColor('red')">new</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';

let color = ref('blue')
function changeColor(val) {
  color.value = val
}
</script>

<style lang="scss">
.home{
  background-color: #fff;
  width: 80vw;
  height: 50vh;
  display: flex;
  align-items: center;
  justify-content: center;
  button{
   width: 100px;
   margin: 10px;
  }
  .btn{
    background-color: v-bind(color);
  }
}
</style>

然后是 js中使用scss定义的变量

新建 global.module.scss文件

$b: blue;
$r: red;

:export {
  BLUR: $b;
  RED: $r;
}

页面中 import引入 global.module.scss 即可


<template>
  <div class="home">
    <button class="btn" @click="changeColor(config.BLUR)">default</button>
    <button class="btn" @click="changeColor(config.RED)">new</button>
  </div>
</template>

<script setup>
import config from '@/common/global.module.scss'
import { ref } from 'vue';

let color = ref('blue')
function changeColor(val) {
  color.value = val
}
</script>

<style lang="scss">
.home{
  background-color: #fff;
  width: 80vw;
  height: 50vh;
  display: flex;
  align-items: center;
  justify-content: center;
  button{
   width: 100px;
   margin: 10px;
  }
  .btn{
    background-color: v-bind(color);
  }
}
</style>

效果

相关文章:

  • asp.net Kestrel 和iis区别
  • 基于OpenCV与PyTorch的智能相册分类器全栈实现教程
  • 耘想WinNAS:以聊天交互重构NAS生态,开启AI时代的存储革命
  • 【后端开发】Spring配置文件
  • ubuntu22.04-VMware Workstation移动后无法连接网络
  • 【视频目标分割论文集】Efficient Track Anything0000
  • 【深度学习与大模型基础】第11章-Bernoulli分布,Multinoulli分布
  • LeetCode 热题 100_单词拆分(86_139_中等_C++)(动态规划)
  • 【从C到C++的算法竞赛迁移指南】第五篇:现代语法糖精粹 —— 写出优雅的竞赛代码
  • 豪越消防一体化安全管控平台:构建消防“一张图”新生态
  • Java Web 300问
  • 大数据(7.4)Kafka存算分离架构深度实践:解锁对象存储的无限潜能
  • STM32基础教程——AD单通道
  • 一款安全好用的企业即时通讯平台,支持统一门户
  • 单链表各种操作实现(数据结构C语言多文件编写)
  • 中介者模式:理论、实践与 Spring 源码解析
  • MDP 值迭代算法
  • AI推理强,思维模型也有功劳【60】启发式偏差思维
  • WITRAN_2DPSGMU_Encoder 类中,门机制
  • 高级语言调用C接口(四)结构体(2)-Python
  • 鄂州交警通报致1死2伤车祸:女子操作不当引发,已被刑拘
  • 首个偏头痛急性治疗药物可缓解前期症状
  • 线下哪些商家支持无理由退货?查询方法公布
  • 飙升至熔断,巴基斯坦股市两大股指收盘涨逾9%
  • 梅花奖在上海|“我的乱弹我的团”,民营院团首次入围终评
  • 水豚出逃40天至今未归,江苏扬州一动物园发悬赏公告