vue3 自定义网站title的hooks

在开发网页的时候会遇到,每个页面需要有自己的标题的需求,这样的话每个页面都需要写重复的代码。

通过hooks封装之后,页面上只需要一行代码就能搞定。

具体实现代码如下:

封装的title hooks

javascript 复制代码
import { ref,watchEffect,onUnmounted } from 'vue'

export function useTitle(title:string,restoreOnUnMount = true){
    const cTitle = document.title;
    const titleRef = ref(title);
    watchEffect(()=>{
        document.title = titleRef.vaule;
    })
    if(restoreOnUnMount){
        onUnmounted(() => {
            document.title = cTitle;
        })
    }
    const setTitle = (title:string) =>{
        titleRef.value = title;
    }
    return setTitle
}

在页面引入hooks,写下边代码

javascript 复制代码
const setTitle = useTitle('测试标题')
相关推荐
胡萝卜术7 小时前
从API调用到手写LRU:力扣146「LRU缓存」的哈希表+双向链表终极进化之路
前端·javascript·面试
科技道人7 小时前
记录 默认置灰/禁用 app ‘Search Engine Selector‘ 的disable按钮
开发语言·前端·javascript
天疆说7 小时前
Zotero Connector 在 Edge 里找不到桌面 Zotero(Linux / Zotero 9.0.6 / Edge 150)
linux·前端·edge
李伟_Li慢慢8 小时前
02-从硬件说起WebGL
前端·three.js
kyriewen9 小时前
看了微软几万人用AI编程的数据——效率涨24%的代价没人提
前端·ai编程·claude
2601_963771379 小时前
How to Scale Your WordPress Store Traffic in 2026
前端·php·plugin
亿元程序员9 小时前
老板说我的3D箭头游戏用来做试玩太普通了,没人想玩,让我变点花样...
前端
李伟_Li慢慢10 小时前
01-threejs架构原理-课程简介
前端·three.js
_瑞11 小时前
深入理解 iOS 渲染原理
前端·ios
IT_陈寒11 小时前
SpringBoot自动配置失灵?你可能忘了这个关键注解
前端·人工智能·后端