vue.js在App.vue中获取路由名称 [英] vue.js get route name in App.vue
问题描述
我使用vue-cli和webpack来构建vue项目。
然后我安装了vue-meta-info来设置seo。
I used vue-cli with webpack to build up the vue project. Then I installed vue-meta-info to set up the seo.
我想用模板和路由名称设置页面标题。
但是,我无法在路由器中获取变量。
I want to set up the Page title with the templates and the route name. However , I cannot get the variable in router.
rotuer / index.js
import Vue from 'vue';
import Router from 'vue-router';
import HelloWorld from '@/components/HelloWorld';
Vue.use(Router);
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld,
},
],
});
App.vue
<template>
<div id="app">
<router-view/>
</div>
</template>
<script>
export default {
name: 'App',
metaInfo: {
title: "My Website - "+ route.name,
},
};
</script>
推荐答案
您可以使用路由器的 beforeEach()
helper。
You can use the router's beforeEach()
helper.
示例:
import Foo from '@/components/Foo'
export default new VueRouter({
mode: 'history',
routes: [
{
path: '/',
name: 'Foo',
component: Foo,
meta: {
title: 'Foo'
}
}
]
})
在 app.js
或 main.js
或任何你的主要Javascript文件是。将代码放在上述JS文件之一中将允许所有页面相应地更新标题,并且是处理标题的更清晰的方式。
In app.js
or main.js
or whatever your main Javascript file is. Placing the code in one of the aforementioned JS file will allow all pages to update the title accordingly and is a much cleaner way to handle the titles.
import router from '@/routes'
// your other codes here
router.beforeEach((to, from, next) => {
document.title = `My website - ${to.meta.title}`
next()
})
这篇关于vue.js在App.vue中获取路由名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!