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');
}
相关推荐
qq4356947015 小时前
Vue04
前端·vue.js
Yeats_Liao6 小时前
Feed流系统设计(三):数据模型与存储设计,从表结构到Redis收件箱
java·javascript·redis
我是真菜6 小时前
彻底理解js中的深浅拷贝
前端·javascript
尽兴-8 小时前
4.1 智能体核心:Agent、Sub-Agent、ReAct、规划执行
前端·javascript·react.js·agent·react·subagent
万物更新_8 小时前
vue框架
前端·javascript·vue.js·笔记
Richar8 小时前
Object.freeze()注意事项
前端·javascript
TA远方8 小时前
【HTML】JavaScript Canvas 图像截取与保存完整指南
前端·javascript·html·canvas·截图·截取
Asize8 小时前
JavaScript 数据类型解析:从 null 与 undefined 的迷思到栈堆内存真相
前端·javascript·面试
LDX前端校草9 小时前
position属性值及用法
前端·javascript·面试
晓13139 小时前
【Cocos Creator 3.x】篇——第四章 子系统
前端·javascript·游戏引擎