运用Vue Router的进程守护修改单页的title

276 阅读1分钟

引入vue-router

import Vue from 'vue'
import Router from 'vue-router'

在routes配置title

routes: [
    {          /* (首页)默认路由地址 */
      path: '/',
      name: 'index',
      component: Index,
      meta: {
        title: '首页'
      }
    },
    {          /* 列表 */
      path: '/list',
      name: 'list',
      component: list,
      meta: {
        title: '列表'
      }
    },
    {          /* 详情 */
      path: '/detail',
      name: 'detail',
      component: goodsDetail,
      meta: {
        title: '详情'
      }
    },
    { /* Not Found 路由,必须是最后一个路由 */
      path: '*',
      component: NotFound,
      meta: {
        title: '找不到页面'
      }
    }
  ]    

利用vue-router的进程守护,在进入每个页面的时候重置title

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