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');
}
相关推荐
小彭努力中16 小时前
191.Vue3 + OpenLayers 实战:可控化版权信息(Attribution)详解与完整示例
前端·javascript·vue.js·#地图开发·#cesium
朝阳58116 小时前
控制 Nuxt 页面的渲染模式:客户端 vs 服务端渲染
前端·javascript
发现一只大呆瓜16 小时前
Vue-Vue2与Vue3核心差异与进化
前端·vue.js·面试
发现一只大呆瓜17 小时前
Vue2:数组/对象操作避坑大全
前端·vue.js·面试
发现一只大呆瓜17 小时前
Vue3:ref 与 reactive 超全对比
前端·vue.js·面试
程序猿大波18 小时前
基于java,SpringBoot和Vue餐饮公司食堂管理系统设计
java·vue.js·spring boot
swipe18 小时前
JavaScript 对象操作进阶:从属性描述符到对象创建模式
前端·javascript·面试
前端小趴菜0519 小时前
vue3项目优化方案
前端·javascript·vue.js
Irene199120 小时前
对比总结:Vue3中的 watch 和 Pinia中的 $subscribe
vue.js·pinia·watch·subscribe
Luna-player20 小时前
gitee上的vue项目,刚刚创建了一个分支,怎么在本地上拉取分支项目
前端·vue.js·gitee