vue修改浏览器的标题title

博客介绍了三种更改页面标题的方法。方法一是在main.js添加全局指令,在组件div中加入代码;方法二是利用路由导购守卫beforeEach,在route里给路由加meta属性,在main.js加导航守卫;方法三是安装并引用插件,在路由配置文件配置标题,添加指令。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一:

第一步:在main.js里面添加一个全局指令

Vue.directive('title', {
  inserted: function (el, binding) {
    document.title = el.dataset.title
  }
})

第二步:在要调用的组件里面,随便找一个div加入如下代码

v-title data-title="我的"

案例:

<template>
    <header class="header_home user_reg" v-title data-title=""> 
   <div class="top_box hidden-xs"> 
    <div class="container"> 
      <router-link to="/" class="logo"> 
        <img src="../../../assets/image/5b10f166c3332.png" alt="" /> 
      </router-link> 
     <ul class="navs">
        <li>
            <router-link to="/regist">注册</router-link>
        </li> 
        <li>
          <router-link to="/login">登录</router-link>
        </li> 
        <li>
          <router-link to="/CooperUser">合作平台</router-link>
        </li> 
     </ul> 
    </div> 
   </div> 
  </header>
</template>

方法二:

实现思路很简单:就是利用路由的导购守卫beforeEach在每次页面跳转前更改对应的title

第一步:首先在route里面给每个路由加上meta属性

{
            path: '/login',
            name: 'login',
            component(resolve) {
                require(['./views/login.vue'], resolve)
            },
            meta: {
                title: '登录页',
                keepAlive: true, // 需要被缓存
            }
        },
        {
            path: '/regist',
            name: 'regist',
            component(resolve) {
                require(['./views/regist.vue'], resolve)
            },
            meta: {
                title: '注册页',
                keepAlive: true, // 需要被缓存
            }
        },
        {
            path: '/newList',
            name: 'newlist',
            component(resolve) {
                require(['./views/newsList.vue'], resolve)
            },
            meta: {
                title: '新闻列表',
                keepAlive: true, // 需要被缓存
            }
        }

第二步:在main.js里面加上导航守卫

router.beforeEach((to, from, next) => {
    window.document.title = to.meta.title == undefined?'默认标题':to.meta.title
    if (to.meta.requireAuth) {
        let token = Cookies.get('access_token');
        let anonymous = Cookies.get('user_name');
        if (token) { 
            
                next({
                    path: '/login',
                    query: {
                        redirect: to.fullPath
                    } 
                })
          
        }
    }
    next();
})

方法三:

1.先安装插件,命令行执行cnpm install vue-wechat-title --save即可安装。 
2.引用插件,在main.js中,首先import然后再use即可,具体代码如下:

import VueWechatTitle from 'vue-wechat-title'
Vue.use(VueWechatTitle)

3.在路由的配置文件router.js里面配置我们想要的页面标题,代码示例如下:

routes: [{
            path: '/',
            name: 'index',
            component: Index,
            meta: {
                title: "漫岛-一个有趣的网站"
            }
        },
        {
            path: '/recruit',
            name: 'recruit',
            component: Recruit,
            meta: {
                title: "漫岛-团队伙伴招募"
            }
        }
    ]

4.最后一步,在app.vue里面添加指令v-wechat-title即可,示例是从官方npm页面copy的,请注意注释部分不要破坏使用规则。具体如下:

<!-- 任意元素中加 v-wechat-title 指令 建议将标题放在 route 对应meta对象的定义中 -->
<div v-wechat-title="$route.meta.title"></div>
<!--或者-->
<router-view v-wechat-title="$route.meta.title"></router-view>

 

<think>在Vue3修改浏览器标题和favicon有多种方法,下面将详细介绍几种常用方案: ### 方法一:直接修改public/index.html(静态设置) 适用于固定标题和图标的应用,修改`public/index.html`文件: ```html <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <link rel="icon" href="<%= BASE_URL %>favicon.ico"> <!-- 图标路径 --> <title>我的应用标题</title> <!-- 固定标题 --> </head> <body> <div id="app"></div> </body> </html> ``` > 注意:此方法为静态设置,无法实现动态更新[^4] ### 方法二:使用document API动态修改(推荐) 在Vue组件或工具函数中通过DOM API动态修改: #### 1. 修改标题 ```javascript // 在任何Vue组件中 document.title = "新的页面标题"; ``` #### 2. 修改favicon ```javascript const changeFavicon = (iconUrl) => { // 查找现有图标或创建新元素 let link = document.querySelector("link[rel*=&#39;icon&#39;]") || document.createElement(&#39;link&#39;); // 设置属性 link.type = &#39;image/x-icon&#39;; link.rel = &#39;shortcut icon&#39;; link.href = iconUrl; // 添加到head document.head.appendChild(link); }; // 使用示例 changeFavicon(&#39;/path/to/new-favicon.ico&#39;); ``` ### 方法三:使用Vue响应式结合生命周期(动态更新) 结合路由变化动态更新标题: ```javascript // router/index.js import { createRouter } from &#39;vue-router&#39; const routes = [ { path: &#39;/&#39;, component: Home, meta: { title: &#39;首页&#39; } // 添加标题信息 }, { path: &#39;/about&#39;, component: About, meta: { title: &#39;关于我们&#39; } } ]; const router = createRouter({ /* 配置 */ }); // 全局前置守卫动态设置标题 router.beforeEach((to, from, next) => { if (to.meta.title) { document.title = `${to.meta.title} - 我的应用`; } next(); }); ``` ### 方法四:使用第三方库(高级需求) 对于复杂应用,推荐使用专门的头管理库: ```bash npm install @vueuse/head ``` ```javascript // main.js import { createHead } from &#39;@vueuse/head&#39; const head = createHead() app.use(head) // 组件内使用 import { useHead } from &#39;@vueuse/head&#39; export default { setup() { useHead({ title: &#39;动态标题&#39;, link: [{ rel: &#39;icon&#39;, type: &#39;image/svg+xml&#39;, href: &#39;/dynamic-icon.svg&#39; }] }) } } ``` ### 微信浏览器兼容处理 在微信内置浏览器中动态修改标题可能需要特殊处理: ```javascript function setWechatTitle(title) { document.title = title; // 兼容微信WebView const ua = navigator.userAgent.toLowerCase(); if (/iphone|ipad|ipod/.test(ua)) { const iframe = document.createElement(&#39;iframe&#39;); iframe.src = &#39;/favicon.ico&#39;; iframe.style.display = &#39;none&#39;; iframe.onload = () => { setTimeout(() => { document.body.removeChild(iframe); }, 0); }; document.body.appendChild(iframe); } } ``` ### 完整工具函数示例 ```javascript // utils/headUtils.js export const setPageTitle = (title) => { document.title = title; // iOS微信兼容处理 if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) { const iframe = document.createElement(&#39;iframe&#39;); iframe.src = &#39;/favicon.ico&#39;; iframe.style.display = &#39;none&#39;; document.body.appendChild(iframe); setTimeout(() => { document.body.removeChild(iframe); }, 0); } }; export const setFavicon = (url) => { const link = document.createElement(&#39;link&#39;); const oldLinks = document.querySelectorAll(&#39;link[rel*="icon"]&#39;); // 移除旧图标 oldLinks.forEach(link => link.parentNode.removeChild(link)); // 创建新图标 link.type = &#39;image/x-icon&#39;; link.rel = &#39;shortcut icon&#39;; link.href = url; document.head.appendChild(link); }; ``` ### 使用注意事项 1. **路径问题**:favicon路径需要使用绝对路径或`<%= BASE_URL %>`前缀 2. **缓存问题**:修改favicon后浏览器可能缓存旧图标,可通过添加查询参数解决: ```javascript setFavicon(&#39;/new-icon.png?v=2&#39;); ``` 3. **SPA应用**:在单页应用中应在路由变化时更新标题 4. **安全性**:动态修改时确保传入参数安全,避免XSS攻击 > 提示:对于使用Vue CLI创建的项目,favicon默认应放在`public/`目录下[^3][^4] ### 最佳实践 ```javascript // 在路由守卫中使用 router.afterEach((to) => { // 设置标题 document.title = to.meta.title || &#39;默认标题&#39;; // 需要时设置图标 if (to.meta.icon) { setFavicon(to.meta.icon); } }); ``` 通过以上方法,您可以在Vue3应用中灵活地控制浏览器标题和图标,满足各种动态设置需求[^1][^2][^5]。 §§相关问题§§ 1. 如何在Vue3中实现路由级别的标题自动更新? 2. 动态修改favicon时如何解决浏览器缓存问题? 3. Vue3中还有哪些操作DOM的推荐方式? 4. 如何为Vue3应用添加PWA图标支持?</think>在 Vue3 中动态修改浏览器标题和图标,可以通过以下几种方法实现: ### 一、修改浏览器标题title) #### 方法1:直接使用 document.title ```javascript // 在任何组件中 document.title = "新的页面标题"; ``` #### 方法2:结合路由守卫动态设置 ```javascript // router.js import { createRouter } from &#39;vue-router&#39; const routes = [ { path: &#39;/dashboard&#39;, component: Dashboard, meta: { title: &#39;控制台&#39; } // 添加标题信息 } ]; const router = createRouter({ ... }); // 全局前置守卫 router.beforeEach((to) => { if (to.meta.title) { document.title = `${to.meta.title} - 我的应用`; } }); ``` ### 二、修改浏览器图标(favicon) #### 方法1:动态修改 link 元素 ```javascript // 工具函数 - 可放在 utils 文件夹中 export function changeFavicon(iconUrl) { // 查找现有图标或创建新元素 let favicon = document.querySelector(&#39;link[rel="icon"]&#39;); if (!favicon) { favicon = document.createElement(&#39;link&#39;); favicon.rel = &#39;icon&#39;; document.head.appendChild(favicon); } // 更新图标URL(添加时间戳防止缓存) favicon.href = `${iconUrl}?t=${new Date().getTime()}`; } // 在组件中使用 import { changeFavicon } from &#39;@/utils/faviconUtils&#39;; changeFavicon(&#39;/new-icon.ico&#39;); // 传入新图标路径 ``` #### 方法2:结合 PWA 配置(Vue CLI 项目) ```javascript // vue.config.js module.exports = { pwa: { iconPaths: { favicon32: &#39;src/assets/icons/favicon-32.png&#39;, favicon16: &#39;src/assets/icons/favicon-16.png&#39;, appleTouchIcon: &#39;src/assets/icons/apple-icon.png&#39;, maskIcon: &#39;src/assets/icons/safari-pinned-tab.svg&#39;, msTileImage: &#39;src/assets/icons/mstile-150.png&#39; } } } ``` ### 三、完整示例 - 动态修改标题和图标 ```vue <script setup> import { ref, onMounted } from &#39;vue&#39;; // 响应式标题 const pageTitle = ref(&#39;默认标题&#39;); // 修改标题和图标 const updatePageInfo = (newTitle, newIcon) => { // 更新标题 document.title = newTitle; pageTitle.value = newTitle; // 更新图标 const favicon = document.querySelector(&#39;link[rel="icon"]&#39;) || document.createElement(&#39;link&#39;); favicon.rel = &#39;icon&#39;; favicon.href = newIcon; document.head.appendChild(favicon); }; // 示例:从API获取配置 onMounted(async () => { const config = await fetch(&#39;/api/page-config&#39;).then(res => res.json()); updatePageInfo(config.title, config.faviconUrl); }); </script> <template> <button @click="updatePageInfo(&#39;新标题&#39;, &#39;/new-icon.ico&#39;)"> 更新页面信息 </button> </template> ``` ### 四、微信浏览器兼容处理 在微信内置浏览器中动态修改标题可能需要特殊处理: ```javascript function setWechatTitle(title) { document.title = title; // iOS微信兼容处理 if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) { const iframe = document.createElement(&#39;iframe&#39;); iframe.src = &#39;/favicon.ico&#39;; iframe.style.display = &#39;none&#39;; document.body.appendChild(iframe); setTimeout(() => { document.body.removeChild(iframe); }, 0); } } ``` ### 五、最佳实践建议 1. **图标格式**: - 推荐使用 PNG 格式(尺寸:32x32、64x64) - 兼容方案:同时提供 ICO 格式 2. **缓存问题**: ```javascript // 在URL中添加时间戳防止缓存 favicon.href = `${iconUrl}?t=${new Date().getTime()}`; ``` 3. **多尺寸适配**: ```html <!-- 在 public/index.html 中预定义 --> <link rel="icon" type="image/png" sizes="32x32" href="<%= BASE_URL %>favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="<%= BASE_URL %>favicon-16x16.png"> ``` 4. **动态路由集成**: ```javascript // 在路由配置中添加元信息 { path: &#39;/user/:id&#39;, component: UserProfile, meta: { title: (route) => `用户 ${route.params.id} 的资料`, icon: &#39;/user-icon.png&#39; } } ``` ### 六、完整工具函数封装 ```javascript // utils/pageUtils.js export const setPageTitle = (title) => { document.title = title; // 微信iOS兼容处理 if (/MicroMessenger/i.test(navigator.userAgent) && /iOS/i.test(navigator.platform)) { const iframe = document.createElement(&#39;iframe&#39;); iframe.src = &#39;/favicon.ico&#39;; iframe.style.display = &#39;none&#39;; document.body.appendChild(iframe); setTimeout(() => document.body.removeChild(iframe), 100); } }; export const setFavicon = (url) => { const link = document.createElement(&#39;link&#39;); const oldLinks = document.querySelectorAll(&#39;link[rel*="icon"]&#39;); // 移除旧图标 oldLinks.forEach(link => link.parentNode.removeChild(link)); // 创建新图标(添加时间戳防缓存) link.type = &#39;image/x-icon&#39;; link.rel = &#39;shortcut icon&#39;; link.href = `${url}?t=${Date.now()}`; document.head.appendChild(link); }; // 使用示例 import { setPageTitle, setFavicon } from &#39;@/utils/pageUtils&#39;; setPageTitle(&#39;用户控制台&#39;); setFavicon(&#39;/assets/icons/admin.ico&#39;); ``` 通过以上方法,您可以在 Vue3 应用中灵活地动态修改浏览器标题和图标。根据实际需求选择简单直接的 DOM 操作,或结合路由守卫实现更自动化的标题管理[^1][^2][^5]。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值