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 小时前
Day 3 · Agent Loop:从调用模型到控制循环 —— 课件精讲笔记
服务器·开发语言·javascript·数据库·人工智能·笔记·ecmascript
夕水2 小时前
我把颜色选择器拆成了 15 个插件,最后长成了 22 个包
前端·javascript·typescript
用户88956195481713 小时前
戴上眼镜就把今天听完:绿光快报的 AIUI 语音新闻智能体
javascript
stormsha3 小时前
ResizeObserver loop completed with undelivered notifications:它只是个警告,但也是你代码的供词
javascript·css
Nazarick4 小时前
从 fetch 到 then:Demo在线订单系统 Ajax 回调的逐帧拆解
java·javascript·ajax·web
徐同保6 小时前
模板里的图标组件找不到定义?聊聊 @tabler/icons-vue 与自动导入
前端·javascript·vue.js
橙光成长7 小时前
GameScrcpy:不装模拟器,用键鼠手柄和 TypeScript 脚本接管你的安卓手游
android·javascript·typescript·开源·1024程序员节
米米商聊8 小时前
AI 搜群附件,同一份 PDF 占满前三条?按附件 ID 折叠片段
javascript·人工智能
代码小学生&8 小时前
IIS 反向代理配置完整流程
javascript