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');
}
相关推荐
像我这样帅的人丶你还1 天前
别再让JS耽误你进步了。
css·vue.js
@yanyu6661 天前
07-引入element布局及spring boot完善后端
javascript·vue.js·spring boot
王霸天1 天前
💥别再抄网上的Scale缩放代码了!50行源码教你写一个永不翻车的大屏适配
前端·vue.js·数据可视化
@大迁世界1 天前
2026年React大洗牌:React Hooks 将迎来重大升级
前端·javascript·react.js·前端框架·ecmascript
悟空瞎说1 天前
深入 Vue3 响应式:为什么有的要加.value,有的不用?从设计到源码彻底讲透
前端·vue.js
风止何安啊1 天前
为什么要有 TypeScript?让 JS 告别 “薛定谔的 Bug”
前端·javascript·面试
海天鹰1 天前
SOC架构
javascript
前进的李工1 天前
MySQL角色管理:权限控制全攻略
前端·javascript·数据库·mysql
NPE~1 天前
[App逆向]环境搭建下篇 — — 逆向源码+hook实战
android·javascript·python·教程·逆向·hook·逆向分析
洒满阳光的庄园1 天前
Electron 桌面端打包流程说明
前端·javascript·electron