个人技术分享

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

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

具体实现代码如下:

封装的title hooks

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,写下边代码

const setTitle = useTitle('测试标题')