本文使用的技术主要包括 vue3+vite+scss

1.配置全局scss变量

 首先在src目录下创建styles文件夹,并新建common.scss文件,内容如下:

// 文字颜色
$fontColor: var(--font-color, #333);
// 盒子背景
$boxBgColor: var(--bg-color, #ccc);

 修改vite.config.ts文件,引入全局scss文件,内容如下:

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
      'components': path.resolve(__dirname, './src/components'),
    }
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@import '@/styles/common.scss';` // 引入全局变量文件
      }
    }
  }
})

2.主题控制方法

在src下的hooks文件夹下,新建 changeColor.ts 文件,内容如下:


// 修改主题
import { ref } from 'vue';
const useThem = () => {
    const isDarkThem = ref(false); // 是否是暗黑主题
    // 主题切换
    const changeThem = () => {
        if (isDarkThem.value) {
            document.getElementsByTagName('body')[0].style.setProperty('--font-color', '#fff');
            document.getElementsByTagName('body')[0].style.setProperty('--bg-color', '#000');
        } else {
            document.getElementsByTagName('body')[0].style.setProperty('--font-color', '#333');
            document.getElementsByTagName('body')[0].style.setProperty('--bg-color', '#ccc');
        }
    }
    return { isDarkThem, changeThem }
}

export { useThem };

3.页面使用

引入主题控制方法,使用按钮进行主题切换,内容如下:


<template>
  <div class="testPage">
    <div class="box">
      <span>测试文字</span>
    </div>
    <el-switch v-model="isDarkThem" class="mb-2" active-text="黑夜" inactive-text="白天" @change="changeThem" />
  </div>
</template>
<script setup lang="ts">
import { useThem } from '@/hooks/changeColor'
const { isDarkThem, changeThem } = useThem();


</script>
<style scoped lang="scss">
.box {
  background-color: $boxBgColor; // 全局变量
  width: 200px;
  height: 200px;
  margin: 0 auto 20px;
  line-height: 200px;
  text-align: center;

  span {
    color: $fontColor;  // 全局变量
  }
}
</style>

4.效果展示:

展示切换开关的效果,实现主题切换功能 

 

Logo

前往低代码交流专区

更多推荐