效果预览
- 页码加载时,自动获取网页标题
- 通过input输入框,可以实时改变网页标题
代码实现
index.vue
<template> <h1>网页的标题为: {{ titleRef }}</h1> <p>通过input输入框实时改变网页的标题 <input v-model="titleRef" /></p> </template> <script setup> import useTitle from "./hooks/useTitle.js"; const titleRef = useTitle(); </script>
useTitle.js
import { ref, onMounted, watch } from "vue"; function useTitle() { let titleRef = ref(""); onMounted(() => { titleRef.value = document.title; }); watch(titleRef, (newVal, oldVal) => { if (newVal !== oldVal) { document.title = newVal; } }); return titleRef; } export default useTitle;