vue3+less使用主题定制(多主题定制)可切换主题

假如要使用两套主题:蓝色、红色

例如:

首先确保自己的vue3项目有less,这边不多做接入解释

1、在src目录下建一个styles文件夹,在syles文件夹下面新建两个less文件:theme.less和variables.less;

theme.less的样式代码(默认的主题色):

css 复制代码
@import './variables.less';

:root {
	--primary-color: #e83d23; // 默认主题颜色
}

variables.less的样式代码(供切换的主题,可以制作多种,我这边只做两种):

css 复制代码
.red-theme {
	--primary-color: #e83d23;
}

.blue-theme {
	--primary-color: #4c7bec;
}

2、使用vuex来管理,这边vuex怎么接入就不过多叙述,请先接入vuex;然后直接粘贴我里面的全部代码

store下面的index代码:

javascript 复制代码
import { createStore } from 'vuex'

// 持久化的插件
import createPersistedState from "vuex-persistedstate"


const state = {
    // 当前的主题
	currentTheme: 'red-theme',
}
const getters = {
}
const mutations = {
    // 切换主题的方法
	switchTheme(state, theme) {
		state.currentTheme = theme;
	},
}
const actions = {
    // 异步切换主题
	switchTheme({ commit }, theme) {
		commit('switchTheme', theme);
	},
}

const modules = {
	
}

export default createStore({
	state,
	mutations,
	actions,
	getters,
	modules,
	plugins: [createPersistedState()],
})

3、在App.vue里面的顶层div使用我当前的样式class,这边直接粘贴代码:

App.vue:

javascript 复制代码
<template>
	<div :class="currentTheme">
		<router-view v-slot="{ Component }">
			<keep-alive>
				<component :is="Component" v-if="$route.meta.keepAlive" />
			</keep-alive>
			<component :is="Component" v-if="!$route.meta.keepAlive" />
		</router-view>
	</div>
</template>

<script lang="ts">
	import { defineComponent } from 'vue'
	import { mapState } from 'vuex'

	export default defineComponent({
		name: 'App',
		components: {},
		computed: {
			...mapState(['currentTheme']),
		}
	})
</script>

主要代码是最外层div上面绑定的class,下面的router-view你们项目是怎样的就是怎样的,不用和我的一样,然后再是下面的计算属性,引入vuex里面的主题变量

4、在页面代码里面使用切换功能,就可以切换了,例如:

index.vue:

javascript 复制代码
<template>
    <div>
		<button @click="switchTheme('red-theme')">点击切换为红色</button>
		<button @click="switchTheme('blue-theme')">点击切换为蓝色</button>
		<div class="test">测试切换主题</div>
	</div>
</template>

<script setup>
    import { ref } from 'vue';
    import { useStore } from 'vuex'
    const store = useStore()
    
    const currentTheme = ref('red-theme');
	const switchTheme = (theme) => {
		store.commit('switchTheme', theme)
	}
</script>
<style lang="less" scoped>
    .test {
        // 使用第一步定义的样式变量
		color: var(--primary-color);
	}
</style>

至此就可以了,其实思路很简单:就是在根目录上面绑定样式,通过切换这个样式来做到主题的切换,如果使用的主题量很大,是不是就得考虑性能问题了...

相关推荐
「、皓子~19 分钟前
后台管理系统的诞生 - 利用AI 1天完成整个后台管理系统的微服务后端+前端
前端·人工智能·微服务·小程序·go·ai编程·ai写作
就改了21 分钟前
Ajax——在OA系统提升性能的局部刷新
前端·javascript·ajax
凌冰_23 分钟前
Ajax 入门
前端·javascript·ajax
京东零售技术38 分钟前
京东小程序JS API仓颉改造实践
前端
奋飛1 小时前
TypeScript系列:第六篇 - 编写高质量的TS类型
javascript·typescript·ts·declare·.d.ts
老A技术联盟1 小时前
从小白入门,基于Cursor开发一个前端小程序之Cursor 编程实践与案例分析
前端·小程序
风铃喵游1 小时前
构建引擎: 打造小程序编译器
前端·小程序·架构
sunbyte1 小时前
50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | ThemeClock(主题时钟)
前端·javascript·css·vue.js·前端框架·tailwindcss
小飞悟1 小时前
🎯 什么是模块化?CommonJS 和 ES6 Modules 到底有什么区别?小白也能看懂
前端·javascript·设计
浏览器API调用工程师_Taylor1 小时前
AOP魔法:一招实现登录弹窗的全局拦截与动态处理
前端·javascript·vue.js