運用Vue Router的程式守護修改單頁的title

花竹果發表於2018-08-02

引入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()
})
複製程式碼

相關文章