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>

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

相关推荐
蚂小蚁6 分钟前
一文吃透:宏任务、微任务、事件循环、浏览器渲染、Vue 批处理与 Node 差异(含性能优化)
前端·面试·架构
狼性书生18 分钟前
uniapp实现的Tab 选项卡组件模板
前端·uni-app·vue·组件·插件
吃饺子不吃馅23 分钟前
前端画布类型编辑器项目,历史记录技术方案调研
前端·架构·github
许___23 分钟前
el-table多选模式下跨分页保留当前页选项
javascript·vue.js
拜晨38 分钟前
使用motion实现小宇宙贴纸墙效果
前端·交互设计
梦想平凡42 分钟前
情怀源代码工程实践(加长版 1/3):确定性内核、事件回放与最小可运行骨架
开发语言·javascript·ecmascript
拜晨1 小时前
使用motion实现小宇宙节目广场的效果
前端·交互设计
爱吃甜品的糯米团子1 小时前
详解 JavaScript 内置对象与包装类型:方法、案例与实战
java·开发语言·javascript
知花实央l1 小时前
【Web应用实战】 文件上传漏洞实战:Low/Medium/High三级绕过(一句话木马拿webshell全流程)
前端·学习·网络安全·安全架构
华仔啊1 小时前
JavaScript + Web Audio API 打造炫酷音乐可视化效果,让你的网页跟随音乐跳起来
前端·javascript