Vue同个路由跳转到不同的页面设置title

384 阅读1分钟

方法:

直接获取不同参数,用document.title = 参数值;进行修改

对于iOS中document.title失效的解决方法

在router文件夹index.js中

// 省略...
const router = new Router({
    routes:[
        // 省略...
    ]
})
router.afterEach(route => {
  // 从路由的元信息中获取 title 属性
  if (route.meta.title) {
    document.title = route.meta.title

    // 如果是 iOS 设备,则使用如下 hack 的写法实现页面标题的更新
    if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
      const hackIframe = document.createElement('iframe')
      hackIframe.style.display = 'none'
      hackIframe.src = '/robots.txt?r=' + Math.random()

      document.body.appendChild(hackIframe)

      setTimeout(_ => {
        document.body.removeChild(hackIframe)
      }, 300)
    }
  }
})
export default router

原文链接:segmentfault.com/a/119000000…