Vue动态修改网页标题

业务需求,进入页面的时候,网页有个默认标题,加载的网页内容不同时,标题需要变更. 例:功能授权,功能授权(张三).

Vue下有很多的方式去修改网页标题,这里总结下解决此问题的几种方案:

一、最笨方案

结合业务直接在Vue生命周期函数 created 和 mounted 中,给 document.title赋值。

  1. <script>
  2. import axios from 'axios'
  3. export default {
  4.   created () {
  5.     document.title = '功能授权'
  6.   },
  7.   mounted() {
  8.     axios.get('***').then((d)=>{
  9.    document.title = '功能授权('+ d.Name + ')'
  10.     })
  11.   }
  12. }
  13. </script>

     

二、普通方案,使用Vue-Router的beforeEach拦截

项目中使用了Vue Router,在路由文件 index.js 中给需要的路由添加 title。

  1. routes: [{
  2.       path: '/',
  3.       name: 'home',
  4.       component: () => import('@/pages/home/index'),
  5.       meta:{
  6.         keepAlive: true
  7.       }
  8.     },
  9.     {
  10.       path: '/person/auth,
  11.       name: 'personAuth',
  12.       component: () => import('@/pages/person/auth),
  13.       meta:{
  14.         title: '功能授权',
  15.         keepAlive: false
  16.       }
  17.     }
  18.   ]

在路由的beforeEach 拦截器里处理

  1. router.beforeEach((to, from, next) => {
  2.   /* 路由发生变化修改页面title */
  3.   if (to.meta.title) {
  4.     document.title = to.meta.title
  5.   }
  6. })

如果想在页面上依据加载的内容不同再变更title时,请参考方式一的 mounted函数处理逻辑.

三、优雅方案,使用Vue 自定义指令(directive)

如前文所提,页面获取不同数据状态时,需要展示不同的标题。那么我们可以结合vue 自定义指令(directive)可更优雅的处理网页标题的动态更新。

自定义指令 v-web-title的定义

  1. export default {
  2.   inserted: function (el, binding) {
  3.     const { value } = binding
  4.     if (el.dataset.title) { // 方式1,可以给标签的data-title的属性赋值
  5.       document.title = el.dataset.title
  6.     } else if (value && value.title) { // 方式2,指令传参
  7.       document.title = value.title
  8.     }
  9.   },
  10.   update (el, binding, vnode, oldVnode) {
  11.     const { value } = binding
  12.     if (el.dataset.title) {
  13.       document.title = el.dataset.title
  14.     } else if (value && value.title) {
  15.       document.title = value.title
  16.     }
  17.   }
  18. }

在页面上使用v-web-title有两种方式

1.给标签 data-title属性赋值

  1. <template>
  2.   <div v-web-title
  3.        :data-title="textTitle">
  4. </template>
  5. <script>
  6. import axios from 'axios'
  7. export default {
  8.   data(){
  9.     return {
  10.       textTitle:'功能授权'
  11.     }
  12.   },
  13.   mounted () {
  14.     axios.get('***').then((d) => {
  15.       this.textTitle = '功能授权(' + d.Name + ')'
  16.     })
  17.   }
  18. }
  19. </script>

2.给指令传参

  1. <template>
  2.   <div v-web-title="{title:textTitle}">
  3. </template>
  4. <script>
  5. import axios from 'axios'
  6. export default {
  7.   data(){
  8.     return {
  9.       textTitle:'功能授权'
  10.     }
  11.   },
  12.   mounted () {
  13.     axios.get('***').then((d) => {
  14.       this.textTitle = '功能授权(' + d.Name + ')'
  15.     })
  16.   }
  17. }
  18. </script>

四、参考

1. vue单页面应用中动态修改title 主要介绍使用vue-weachat-title 组件

2.vue.js自定义指令详解 主要介绍自定义指令的钩子函数,以及指令传参等

posted @ 2019-06-08 16:31  沉淀的风  阅读(22796)  评论(1编辑  收藏  举报