vue3如何实现换肤效果(精简版)

895 阅读2分钟

简要

换肤这个功能在很多网站中还是挺常见的,这个功能看起来很庞大繁杂的感觉,但是其实你只要弄清楚其中的实现思路,就很容易攻克这个难题。下面我就说一下我实现的大致思路:

实现思路

首先我们要理解换肤的本质,就是那些地方需要改变,那些地方不需要我们去改变。这个就很好理解,切换主题和皮肤,无非就是背景色、字体的颜色发生了变化,所以我们的根本目的就是要改变背景色和字体颜色这些属性实现切换的效果。下面我用一个很简单的demo来为大家展示一下效果。

具体实现

定义主题文件

我们想要切换不同的主题,肯定要改变背景色、字体色等等这些属性的属性值,那我们一一去替换肯定是不现实的,那怎么实现呢?给根元素添加类名,然后在每个类里面定义相同属性定义不同的属性值,那么我们只需要切换的时候改变类名就可以把整体的页面效果给切换了。以下我简单定义了两种:

theme.scss

--winy-bg-color:red;
--winy-color:green;
// 修改elment样式
--el-color-primary: red;
--el-color-white: black;

}
html.theme2{
--winy-bg-color:pink;
--winy-color:blue;
// 修改elment样式
--el-color-primary: green;
--el-color-white: red;

}

正如上述代码所示,你可以定义自己的属性值,也可以修改element的属性值,但是如果要使用自己定义的属性值,你后面使用到的需要切换主题改变的那些样式就要用你定义的变量名来作为属性值,这样才能实现切换效果!

全局引入样式文件

main.ts

import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

*** import './style/theme.scss'

import App from './App.vue'
import router from './router'

在组件中切换类名

test1.vue

<template>
    <div class="ca">
      <el-button type="primary" @click="changeName"
        >change name to 李四</el-button
      >
      <el-button type="primary" @click="changeName2"
        >change name to 张三</el-button
      >
    </div>
    <div class="ca">
      <el-button type="primary" @click="addAge">Add Age</el-button>
      <el-button type="primary" @click="subAge">Subtract Age</el-button>
    </div>
    <div class="theme-test">this is a test</div>
  </div>
</template>

<script setup lang="ts">
const changeTheme = () => {
  const body = document.documentElement as HTMLElement;
  body.setAttribute("class", "theme1");
};
</script>

<style lang="scss" scoped>
.ca {
  padding-top: 20px;
}
.theme-test {
  width: 200px;
  height: 200px;
  background-color: var(--winy-bg-color);
  color: var(--winy-color);
  margin-top: 20px;
}
</style>

效果:

image.png

test2.vue

<template>
  <el-button type="primary">test</el-button>
  <div class="theme-test">this is a test</div>
</template>

<script setup lang="ts">
const changeTheme = () => {
  const body = document.documentElement as HTMLElement;
  body.setAttribute("class", "theme2");
};
</script>

<style lang="scss" scoped>
.theme-test{
  width: 200px;
  height: 200px;
  background-color: var(--winy-bg-color);
  color: var(--winy-color);
  margin-top: 20px;
}
</style>

效果:

image.png

可以看到,上面无论是element还是我自定义的一个容器,他们相应的背景色和字体颜色都发生了改变!到此一个简单的换肤功能就已经实现了。

总结

可能会有一些更复杂的需求,但是基本的实现就是这样,无非就是在这上面做一些补充和添加,如果遇到更复杂的需求,大家就发散一下思维,万变不离其宗嘛! 讲得很简单,希望大家多多支持!有问题随时评论留言。谢谢大家!