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>

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

相关推荐
m0_748233642 分钟前
RabbitMQ 进阶
android·前端·后端
不想有bug的小菜鸟10 分钟前
vue3使用iframe全屏展示pdf效果
前端·pdf
m0_7482386311 分钟前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
u01005596012 分钟前
前端代理,解决跨域问题讲解
前端
quitv17 分钟前
react脚手架配置别名
前端·javascript·react.js
m0_5287238126 分钟前
前端如何进行性能优化
前端·性能优化
化作繁星27 分钟前
在 Vue 3 中,如何缓存和复用动态组件
前端·vue.js·缓存
一粒沙-1 小时前
iOS 将GIF图分享至微信
前端·ios
graywen1 小时前
从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
前端
一只小姜丝3321 小时前
解决各大浏览器中http地址无权限调用麦克风摄像头问题
网络·vue.js·网络协议·http