2016-10-22 24 views
7

我正在使用vue.js v1.0,vue-router v0.7和WebPack構建一個Web應用程序。我遵循Single File Component的模式,併爲每個頁面有不同的組件。Vue.js:爲不同的路線分配頁面標題

我不知道當我瀏覽網頁應用程序頁面時,如何在不同的路線(或可能是不同的組件)中更改頁面標題。我還希望頁面標題在瀏覽器歷史記錄中可用。

回答

3

我也有同樣的問題,前幾天,我決心在我的路線組件定義如下:

export default { 
    created: function() { 
     window.document.title = "Page Title for this route" 
     ... 
    }, 
    ... 
} 

這真的沒有這樣做的正確方法。原因:我做了一個很大的假設,路由組件每次都改變爲新路由時被創建。目前在vue-router的確如此,但未來可能會改變。

我之前在Angular 1.4中使用ui-router,它允許路由組件在內存中生存(粘滯狀態),以便下次路由更改即時。如果vue-router曾執行類似於粘性狀態,我上面在created鉤子中設置標題的方法將失敗。

但直到發生這種情況,您可以使用此解決方案。

7

除了我這裏貼前面的解決方案,還有就是我一點研究後找到了第二個方法:使用Navigation Guards

在我以前的答案詳細,這裏的問題是:vue-router可能會啓動第一次創建後,重新使用路由組件。實際上不需要在路由退出時銷燬這些組件,並在隨後的路由條目中重新創建。因此,我以前的解決方案中的created鉤子可能無法在隨後訪問相同路線時觸發。因此,我們的窗口標題可能無法按預期工作。

爲了解決這個問題,我們可以在路由改變事件上設置窗口標題。路由器實例有一個afterEach掛鉤,在路由更改後被調用。這可以用來設置窗口的標題,詳情如下:

// Let's say this is your router instance, with all "Named Routes" 
const ROUTER_INSTANCE = new VueRouter({ 
    mode: "history", 
    routes: [ 
     { path: "/", name: "HomeComponentName", component: HomeComponent }, 
     { path: "/about", name: "AboutComponentName", component: AboutComponent }, 
     { path: "*", name: "RouteErrorName", component: RouteError } 
    ] 
}) 

// Assign page titles for each of the "named routes" 
// Reason: This allows us to have short named routes, with descriptive title 
const PAGE_TITLE = { 
    "HomeComponentName": "Your Dashboard", 
    "AboutComponentName": "About Us Page", 
    "RouteErrorName": "Error: Page not found" 
} 

ROUTER_INSTANCE.afterEach((toRoute, fromRoute) => { 
    window.document.title = PAGE_TITLE[toRoute.name] 
    console.log(toRoute) // this lets you check what else is available to you here 
}) 

這可能仍然無法幫助你,如果你在類似的航線之間導航,如「/用戶/富」到「/用戶/條」。如果您希望在標題欄中使用用戶名或某些動態頁面特定信息,請查看對中詳述的參數更改的反應。基於文檔,我們應該能夠在組件使用watch如下:

watch: { 
    '$route' (toRoute, fromRoute) { 
     window.document.title = "some page title" 
    } 
} 

希望它能幫助!

1

我有一個解決方案,並用它在我的一個projects

首先創建一個指令。

Vue.directive('title', { 
    inserted: (el, binding) => document.title = binding.value, 
    update: (el, binding) => document.title = binding.value 
}) 

假設我們正在研究'MyComponent.vue'文件。

然後在router-view組件上使用該指令。

<router-view v-title="title" ></router-view> 

export default { 
    data(){ 
    return { 
     title: 'This will be the title' 
    } 
    } 
} 

即使組件更新或頁面重新加載,這也可以工作。

爲我工作得很好!

相關問題