Hooks封装前端主题

主题效果

::: block-1 在VueUse官网中有这样一个效果,就是点击切换按钮,切换页面主题,由白天切换到黑夜。 :::

今天呢我们封装一个简易前端主题Hook,主要分享其中的实现原理。

封装Hooks

准备两个主题样式

js 复制代码
export default {
    fontSize: '20px',
    Color: '#f90',
    backgroundColor: '#eee'
}
themeday.js
js 复制代码
export default {
    fontSize: '20px',
    Color: '#fff',
    backgroundColor: '#333',
}
themedark.js

新建一个hook文件夹,在hook文件夹中新建theme.ts

ts 复制代码
import { ref, type Ref } from 'vue';

// 定义你的主题类型  
interface ThemeType {
    fontSize?: string;
    Color?: string;
    backgroundColor?: string;
}

// 定义你的响应式引用类型  
type ThemedRef = Ref<ThemeType | undefined>;

// 导入你的主题对象  
import themeday from '../utils/themeday.js';
import themedark from '../utils/themedark.js';

// 初始化你的响应式引用  
let Theme: ThemedRef = ref(themeday as ThemeType);

export function useTheme() {
    let Localtheme = localStorage.getItem('theme');
    Theme.value = Localtheme ? JSON.parse(Localtheme) : themeday;

    const changeday = () => {
        Theme.value = themeday;
        localStorage.setItem('theme', JSON.stringify(themeday));
    };
    const changedark = () => {
        Theme.value = themedark;
        localStorage.setItem('theme', JSON.stringify(themedark));
    };

    // 为返回的对象添加类型注释  
    return { Theme, changeday, changedark } as { Theme: ThemedRef; changeday: () => void; changedark: () => void };
}

因为页面会刷新,所以使用localstorage把主题存入,这样切换主题后,即使页面刷新主题也不会再改变。

组件中使用

在组件中引入useTheme

html 复制代码
<template>
   <div>123123123</div>
   <button @click="changeday" style="width: 100px; height: 50px;margin-top: 100px;">明亮模式</button>
   <button @click="changedark" style="width: 100px; height: 50px;">黑暗模式</button>
</template>

<script setup lang="ts">
import { useTheme } from '@/hook/theme'
const { Theme, changeday, changedark } = useTheme()
</script>

引入成功之后该怎样修改页面样式呢?别忘了vue内置指令有一个v-bind 可以动态绑定元素,在js中可以使用,css也可以使用。

css 复制代码
<style scoped lang="scss">
div {
   width: 100px;
   height: 100px;
   border: 1px solid #ccc;
   background-color: v-bind("Theme.backgroundColor");
   font-size: v-bind("Theme.fontSize");
   color: v-bind("Theme.Color");
}
</style>

效果

谢谢观看~

相关推荐
canonical_entropy36 分钟前
下一代低代码渲染框架 nop-chaos-flux 的设计原则
前端·低代码·前端框架
东方小月1 小时前
5分钟搞懂Harness Engineering(驾驭工程):从提示词到AI Agent的进化之路
前端·后端·架构
我叫黑大帅1 小时前
为什么需要 @types/react?解决“无法找到模块 react 的声明文件”报错
前端·javascript·面试
之歆1 小时前
DAY_21JavaScript 深度解析:数组(Array)与函数(Function)(一)
前端·javascript
XinZong2 小时前
【AI社交】基于OpenClaw自研轻量化AI社交平台实战
前端
Le_ee2 小时前
ctfweb:php/php短标签/.haccess+图片马/XXE
开发语言·前端·php
爱上好庆祝2 小时前
学习js的第七天(wed APIs的开始)
前端·javascript·css·学习·html·css3
KaMeidebaby3 小时前
卡梅德生物技术快报|冻干工艺开发:注射用心肌肽全流程参数优化与工程化方案
前端·其他·百度·新浪微博
ooseabiscuit3 小时前
Laravel6.x核心优化与特性全解析
android·开发语言·javascript
哆啦A梦15884 小时前
20, Springboot3+vue3实现前台轮播图和详情页的设计
javascript·数据库·spring boot·mybatis·vue3