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>

效果

谢谢观看~

相关推荐
一把年纪学编程几秒前
【牛马技巧】word统计每一段的字数接近“字数统计”
前端·数据库·word
llc的足迹10 分钟前
el-menu 折叠后小箭头不会消失
前端·javascript·vue.js
九月TTS40 分钟前
TTS-Web-Vue系列:移动端侧边栏与响应式布局深度优化
前端·javascript·vue.js
Johnstons42 分钟前
AnaTraf:深度解析网络性能分析(NPM)
前端·网络·安全·web安全·npm·网络流量监控·网络流量分析
whatever who cares1 小时前
CSS3 伪元素(Pseudo-elements)大全
前端·css·css3
若愚67921 小时前
前端取经路——性能优化:唐僧的九道心经
前端·性能优化
积极向上的龙2 小时前
首屏优化,webpack插件用于给html中js自动添加异步加载属性
javascript·webpack·html
Bl_a_ck2 小时前
开发环境(Development Environment)
开发语言·前端·javascript·typescript·ecmascript
田本初2 小时前
使用vite重构vue-cli的vue3项目
前端·vue.js·重构
ai产品老杨2 小时前
AI赋能安全生产,推进数智化转型的智慧油站开源了。
前端·javascript·vue.js·人工智能·ecmascript