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');
}
相关推荐
从文处安13 小时前
「九九八十一难」组合式函数到底有什么用?
前端·vue.js
前端Hardy13 小时前
面试官:JS数组的常用方法有哪些?这篇总结让你面试稳了!
javascript·面试
yuki_uix13 小时前
Props、Context、EventBus、状态管理:组件通信方案选择指南
前端·javascript·react.js
全栈老石14 小时前
手写无限画布4 —— 从视觉图元到元数据对象
前端·javascript·canvas
用户114896694410514 小时前
VUE3响应式原理——从零解析
vue.js
用户830407130570114 小时前
SPA 首屏加载速度慢怎么解决?
vue.js·webpack
一枚前端小姐姐14 小时前
低代码平台表单设计系统技术分析(实战三)
前端·vue.js·低代码
SuperEugene15 小时前
从 Vue2 到 Vue3:语法差异与迁移时最容易懵的点
前端·vue.js·面试
Leon15 小时前
新手引导 intro.js 的使用
前端·javascript·vue.js
Forever7_16 小时前
仅用一个技巧,让 JavaScript 性能提速 500%!
前端·vue.js