VUE3 换肤/根据主题动态切换图片

1.建立相关主题的less文件\src\assets\style\theme\theme.less

:root[theme='light'] {
--text_primary_color: rgba(34, 34, 48, 1);
--background_primary_color: rgba(255, 255, 255, 1);
...
}

:root[theme='dark'] {
--text_primary_color: rgba(245, 245, 245, 1);
--background_primary_color: rgba(36, 36, 36, 1);
...
}

根据主题建立引入图片

\src\assets\image\dark\
\src\assets\image\light\

2.建立管理主题的js文件 store.js

import { reactive } from 'vue'

export const ThemeStore = reactive({  //使ThemeStore具有响应式,只要theme改变,在组件中使用的ThemeStore就会实时更新,引发页面渲染
    theme: '',
    changeTheme(type) {
        this.theme = type;
        document.documentElement.setAttribute('theme', type);
        localStorage.setItem("Mode", type);   //保存主题到localStorage,保证下次打开还是上次的操作
    },
    getTheme() {
        return this.theme;
    },
    initTheme() {
        const mode = localStorage.getItem('Mode');  //从localStorage获取缓存的主题
        if (mode) {
            this.theme = mode;
            document.documentElement.setAttribute('theme', mode);
        } else {
            this.theme = 'light';
            document.documentElement.setAttribute('theme', 'light');
        }
    },
    getMoreImage() {
        return require(`@/assets/common/` + this.getTheme() + `/more.svg`)  //根据主题获取相应图片
    },

});

3.使用:
初始化主题main.js

import { ThemeStore } from '@/assets/themeStore'
const app = createApp(App)
...
ThemeStore.initTheme()  //初始化

组件中切换主题

import { ThemeStore } from '@/assets/themeStore'
..
ThemeStore.changeTheme('light');
//ThemeStore.changeTheme('dark');

图片引用

import { ThemeStore } from '@/assets/themeStore'

<img :src="ThemeStore.getMoreImage()" />

相关推荐

  1. VUE3 /根据主题动态切换图片

    2024-03-24 21:06:03       48 阅读
  2. vue 一键

    2024-03-24 21:06:03       55 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-24 21:06:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-24 21:06:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-24 21:06:03       82 阅读
  4. Python语言-面向对象

    2024-03-24 21:06:03       91 阅读

热门阅读

  1. 软件测试面试问题总结—CTO面试

    2024-03-24 21:06:03       47 阅读
  2. 小程序调用相机拍照上传

    2024-03-24 21:06:03       37 阅读
  3. python基础练习题5

    2024-03-24 21:06:03       37 阅读
  4. 学习AIGC大模型的步骤

    2024-03-24 21:06:03       42 阅读
  5. 【二进制计算,逆序,每位求和】

    2024-03-24 21:06:03       40 阅读
  6. Python从入门到精通秘籍十七

    2024-03-24 21:06:03       43 阅读
  7. 用C++做一个植物大战僵尸

    2024-03-24 21:06:03       44 阅读
  8. day9 嵌套排序,利用嵌套循环所写的简单时钟

    2024-03-24 21:06:03       35 阅读
  9. LLM推理及加速知识

    2024-03-24 21:06:03       36 阅读