vue暗黑模式

store - models - app.js

在index.js中引入app.js

js 复制代码
import Vue from 'vue'
import Vuex from 'vuex'
import user from "./models/user";
import config from "./models/config";
import app from "./models/app";
Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    user,
    config,
    app
  }
})

app.js

js 复制代码
// 应用主题(通用方法)
const applyTheme = (theme) => {
    localStorage.setItem('theme', theme);
    document.documentElement.setAttribute('data-theme', theme);
    return theme;
};

// 初始化时读取并应用主题
const initTheme = () => applyTheme(localStorage.getItem('theme') || 'light');

const state = {
    messageState: true, // 处理全局弹窗一次性不弹出多个错误弹窗
    theme: initTheme(), // 主题模式:light / dark(初始化时自动应用)
};
const mutations = {
    setMessageState(state) {
        state.messageState = ! state.messageState;
    },
    setTheme(state, theme) {
        state.theme = applyTheme(theme);
    },
    toggleTheme(state) {
        state.theme = applyTheme(state.theme === 'dark' ? 'light' : 'dark');
    }
};
const actions = {
};


export default  {
    state,
    actions,
    mutations
}

在assets里创建dark.less和theme.less,并且在index.less中引入

css 复制代码
@import "./theme";
@import "./dark";

theme.less

css 复制代码
:root{
	//定义正常模式的色值
	--000tofff:#000;
}

dark.less

css 复制代码
:root[data-theme='dark']{
	//定义暗黑模式的色值
	--000tofff:#fff;
}

在样式中使用

css 复制代码
.t{
	color:var(--000tofff);
}

切换正常、暗黑

js 复制代码
change(){
	this.$store.commit('toggleTheme');
}
相关推荐
之歆4 小时前
DAY_12JavaScript DOM 完全指南(二):实战与性能篇
开发语言·前端·javascript·ecmascript
Maimai108084 小时前
React如何用 @microsoft/fetch-event-source 落地 SSE:比原生 EventSource 更灵活的实时推送方案
前端·javascript·react.js·microsoft·前端框架·reactjs·webassembly
candyTong4 小时前
Claude Code 的 Edit 工具是怎么工作的
javascript·后端·架构
卡卡军7 小时前
agmd 1.0 重磅升级——Rust 重写,性能起飞
javascript·rust
Larcher7 小时前
🔥 告别抓瞎:用 Claude Code (cc) 优雅接手与维护已有项目
javascript·机器学习·前端框架
JYeontu7 小时前
轮播图不够惊艳?试下这个立体卡片轮播图
前端·javascript·css
亲亲小宝宝鸭8 小时前
如何监听DOM尺寸的变化?element-resize-detector 和 resizeObserver
前端·javascript
代码煮茶8 小时前
Vite 5.0 新特性深度解析:更快、更干净、更未来的前端构建利器
vue.js
卷帘依旧10 小时前
Generator 全面解析 + async/await 深度对比
前端·javascript
weixin_4713830311 小时前
统一缩放单位基础(px、em、rem)
开发语言·javascript·ecmascript