天天看點

如何用vue-router為每個路由配置各自的title傳統方法使用Vue-Router的方法配置路由

傳統方法

以前在單頁面路由中,就隻能在html檔案中定一個固定的網站的title。如果想要動态的去修改,需要使用如下的方法。

document.title = '這是一個标題';           

這樣會讓我們做很多無用功。顯得十分蠢。

使用Vue-Router的方法

首先打開/src/router/index.js檔案。

找到如下代碼。

const vueRouter = new Router({
    routes,
    mode: 'history',
    linkActiveClass: 'active-link',
    linkExactActiveClass: 'exact-active-link',
    scrollBehavior (to, from, savedPosition) {
      if (savedPosition) {
        return savedPosition;
      } else {
        return { x: 0, y: 0 };
      }
    },
  });           

vueRouter隻是一個變量名。叫什麼可以根據你自己項目的命名來找,隻要是Router執行個體化的一個對象就OK。然後将上述代碼替換成如下代碼。

const vueRouter = new Router({
    routes,
    mode: 'history',
    linkActiveClass: 'active-link',
    linkExactActiveClass: 'exact-active-link',
    scrollBehavior (to, from, savedPosition) {
      if (savedPosition) {
        return savedPosition;
      } else {
        return { x: 0, y: 0 };
      }
    },
  });
  vueRouter.beforeEach((to, from, next) => {
    /* 路由發生變化修改頁面title */
    if (to.meta.title) {
      document.title = to.meta.title;
    }
    next();
  });           

代碼的邏輯就是在路由将要發生變化的時候,用傳統的方法來對每個将要跳轉到的路由的title進行修改。

配置路由

配置好了index.js之後我們就需要去給每個router配置自己的title了。例如。

{
  path: '/',
  name: 'Home',
  component: () => import('@/views/Home/Home'),
  meta: {
    title: '首頁',
  },
}           

給每個路由加上一個叫meta的屬性。meta屬性裡的屬性叫title,也就是每個路由獨特的title了。加上之後,浏覽器裡每個路由都會有自己設定好的title了。

繼續閱讀