2020-07-06 VUE 单页面应用 修改页面title

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2020-07-06 VUE 单页面应用 修改页面title相关的知识,希望对你有一定的参考价值。

参考技术A

地址: vue-weachat-title
解决问题:
1、Vuejs 单页应用在ios系统下部分APP的webview中 标题不能通过 document.title = xxx 的方式修改 该插件只为解决该问题而生(兼容安卓)
2、在vue单页面中,通过浏览器分享到QQ、微信等应用中的链接,只有一个首页标题和默认icon图片

已测试:APP 微信 QQ 支付宝 淘宝

在各个组件中随便一个标签中都可写入

或者

若想要动态改变title值:

自定义加载的图片地址 默认是 ./favicon.ico 可以是相对或者绝对的

汇总:
在详情页中使用,根据不同的文章内容,分享出去的文章标题和图片都不同

设置动态路由

在to.params.title中获取标题 修改

之前做微信公众号项目有的这个需求,需要做到只要是用户分享出去的页面,都自动跳转到一个项目介绍页,避免其他用户点进来,因为没有权限访问,而出现页面空白的情况。
原理也是一样,通过 vue-router 的钩子函数,在路由跳转之前,判断一下是否是从分享页面过来的,如果是就重定向到一个通用的分享页面,如果不是,就正常跳转。

Vue:单页面应用动态设置title

vue开发的单页面应用,需要在进入不同路由时动态改变title

  • vue-cli 3 构建的项目

1.修改public>index.html

修改title标签id为:public_title,后面在路由钩子拦截预处理时会用到

<!DOCTYPE html>
<html lang="en">
  <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 id="public_title">xxx系统</title>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but website doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

2.routes配置增加meta.pagetitle信息

routes: [
    
      path: '/error404',
      name: 'error404',
      meta: 
        pagetitle: '404 Error'
      ,
      component: import('@/views/common/error-page-404.vue')
    
  ]

3.路由钩子拦截,预处理统一设置title

用到Vue路由钩子:beforeEach,通过对象to获取到即将进入的路由的标题(meta.pagetitle),document.getElementById(‘public_title’).innerHTML动态修改标题

/**
 * 全局路由钩子
 * to: 将要进入的,路由对象
 * from:正要离开,路由对象
 */
router.beforeEach((to, from, next) => 
  document.getElementById('public_title').innerHTML = to.meta.pagetitle === undefined ? 'xxx系统' : to.meta.pagetitle
  next();
)

以上是关于2020-07-06 VUE 单页面应用 修改页面title的主要内容,如果未能解决你的问题,请参考以下文章

Vue:单页面应用动态设置title

Vue多页面应用与Nginx

SPA单页面应用router实现

vue-cli配置多页面应用

Vue单页面应用

vue-router实现原理