vue2 单文件组件加入浏览器的title和ico的方法

加入title:

代码:

复制代码
const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

// 在 router/index.js 的导出前添加
router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title;
    
  }
  next();
});

加入ico代码:

复制代码
<template>
  <div>
    <!-- 组件内容 -->
  </div>
</template>

<script>
export default {
  name: 'MyComponent',
  mounted() {
    this.changeFavicon('/new-favicon.ico')
  },
  
  methods: {
    changeFavicon(iconUrl) {
      // 找到现有的 favicon 链接
      let link = document.querySelector("link[rel*='icon']") || document.createElement('link')
      
      // 设置属性
      link.type = 'image/x-icon'
      link.rel = 'shortcut icon'
      link.href = iconUrl
      
      // 添加到 head
      document.getElementsByTagName('head')[0].appendChild(link)
    }
  },
  
  // 离开时恢复原图标
  beforeDestroy() {
    this.changeFavicon('/original-favicon.ico')
  }
}
</script>

解释:

相关推荐
恶猫4 分钟前
网页自动化模拟操作时,模拟真实按键触发事件【终级方案】
前端·javascript·自动化·vue·网页模拟
小羊Yveesss23 分钟前
2026年前端开发新趋势:智能协同、工具革新与场景深耕
前端·ai
Dxy123931021633 分钟前
HTML中的Canvas可以干哪些事情
前端·html
悟乙己36 分钟前
解析 Agent 时代的 HTML PPT SKILLS: html-ppt-skill
前端·html·powerpoint
ZC跨境爬虫37 分钟前
跟着 MDN 学 HTML day_2:(表单分组与高级输入控件实战)
前端·javascript·css·ui·html
ppandss11 小时前
JavaWeb从0到1-DAY4-AJAX
前端·ajax·okhttp
千寻girling1 小时前
滑动窗口刷了快一个月(26天)了 , 还没有刷完. | 含(操作系统学什么的Java 后端)
java·开发语言·javascript·c++·人工智能·后端·python
一袋米扛几楼981 小时前
【报错问题】彻底解决 TypeScript 报错 TS2769: No overload matches this call (JWT 篇)
linux·javascript·typescript
涵涵(互关)1 小时前
语法大全-only-writer-two
前端·vue.js·typescript
huangql5202 小时前
浏览器 Location API、History API、路由记录与支付跳转完全指南
前端