使用vue开发spa应用时,我们会希望页面的title会随着路由的改变而改变。虽然这样对SEO没有多少提升,但是我们还是有这种需求。
使用router的全局守卫api
import Vue from 'vue';
const DEFAULT_TITLE = 'Some Default Title';
router.afterEach((to, from) => {
// Use next tick to handle router history correctly
// see: https://github.com/vuejs/vue-router/issues/914#issuecomment-384477609
Vue.nextTick(() => {
document.title = to.meta.title || DEFAULT_TITLE;
});
});
在组件内部使用watch api
export default {
name: 'App',
watch: {
$route: {
immediate: true,
handler(to, from) {
document.title = to.meta.title || 'Some Default Title';
}
},
}
};