jmo*_*awy 10 javascript vue.js vue-router
我正在使用vue.js v1.0,vue-router v0.7和WebPack构建Web应用程序.我正在遵循单个文件组件模式,并为每个页面提供不同的组件.
当我浏览网页应用页面时,我不知道如何在不同的路线(或可能是不同的组件)中更改页面标题.我还希望在浏览器历史记录中提供页面标题.
Man*_*ani 11
除了我之前发布的解决方案之外,还有一种方法是我在经过一些研究后发现的:使用导航防护
正如我之前的回答中所详述的,问题是:首次创建后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
})
Run Code Online (Sandbox Code Playgroud)
如果您在类似的路线之间导航,例如"/ user/foo"到"/ user/bar",这可能仍然无法帮助您.如果你想在标题栏或一些动态页面的特定信息的用户名,检查了反应到PARAMS变化在详细http://router.vuejs.org/en/essentials/dynamic-matching.html.基于docs,我们应该能够watch在组件中使用如下:
watch: {
'$route' (toRoute, fromRoute) {
window.document.title = "some page title"
}
}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你!
几天前我也遇到了同样的问题,我在路由组件定义中解决如下:
export default {
created: function() {
window.document.title = "Page Title for this route"
...
},
...
}
Run Code Online (Sandbox Code Playgroud)
这确实不是正确的做法。原因:我做了一个很大的假设,每次更改为新路线时都会创建路线组件。目前确实如此vue-router,但将来可能会改变。
ui-router我之前在 Angular 1.4 中使用过,它允许路由组件驻留在内存中(粘性状态),以便下次路由更改是瞬时的。如果vue-router实现了类似于粘性状态的东西,我上面在created钩子中设置标题的方法将会失败。
但在此之前,您可以使用此解决方案。
| 归档时间: |
|
| 查看次数: |
6054 次 |
| 最近记录: |