vue获取页面标题

8/14/2021 Vue工作采坑

# router.js设置标题名称

//引入组件
export default [
  //Home路由
  {
    path:'/',
    // component:Home
    component: () => import('@/views/Home/index'),
  },
  //服务商详情
  {
    path:'/ServiceDetail',
    // component:ServiceDetail
    component: () => import('@/views/ServiceDetail/index'),
    meta: { title:'服务商详情' }
  }, 
  //服务产品详情 ****************
  {
    path:'/Serviceproduct',
    // component:ServiceDetail
    component: () => import('@/views/Serviceproduct/index'),
    meta: { title:'服务产品详情' }
  },
  //路由的重定向
  {
    path:'/',
    redirect: '/'
  }
]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

# main.js 添加如下代码

router.beforeEach((to, from, next) => {
  if (to.meta.title) {
      document.title = to.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 = '/static/html/fixIosTitle.html?r=' + Math.random();
          document.body.appendChild(hackIframe);
          setTimeout(_ => {
              document.body.removeChild(hackIframe)
          }, 300)
      }
      var iframe = document.createElement('iframe');
      iframe.style.visibility = 'hidden';
      iframe.style.width = '1px';
      iframe.style.height = '1px';
      iframe.onload = function () {
          setTimeout(function () {
              document.body.removeChild(iframe);
          }, 0);
      };
      document.body.appendChild(iframe);
      if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
            const hackIframe = document.createElement('iframe');
            hackIframe.style.display = 'none';
            hackIframe.src = '/static/html/fixIosTitle.html?r=' + Math.random();
            document.body.appendChild(hackIframe);
            setTimeout(_ => {
              document.body.removeChild(hackIframe)
            }, 300)
          }
  }
  next()
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Last Updated: 8/20/2021, 5:31:07 PM