laravel 使用 Vue Router 设置页面标题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49999372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:40:23  来源:igfitidea点击:

Set page title with Vue Router

javascriptlaravelvue.jsvue-router

提问by angelique000

I have created a vue-routerwith a page title (h1). Every vue-router link has a meta-title. How can I dynamically set my h1 page title?

我创建了一个带有页面标题 (h1)的vue-router。每个 vue-router 链接都有一个元标题。如何动态设置我的 h1 页面标题?

I have tried $emit, but this is not working in my router. How can I change my page title?

我试过了$emit,但这在我的路由器中不起作用。如何更改我的页面标题?

const dashboard = {
  template: `<div>DASHBOARD</div>`
}
const about = {
  template: `<div>ABOUT</div>`
}

const routes = [
  {path: '/dashboard', component: dashboard, name:'dashboard', meta: { title: 'Dashboard' }},
  {path: '/about', component: about, name:'about', meta: { title: 'About' }}
]
const router = new VueRouter({
  routes // short for routes: routes
})

router.beforeEach((to, from, next) => {
  this.$emit('pagetitle', to.meta.title); // DOESN'T WORK!!
  next();
});

new Vue({
  el: '#app',
  router,
  data() {
    return {
      pagetitle: 'not set'
    }
  },
  watch: {
    '$route': function(value) {
    // I can use things like value.name === 'about', but "watch" doesn't set the page title at the first page load.
    }
  }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
  <router-link to="/dashboard">Dashboard</router-link>
  <router-link to="/about">About</router-link>
  <router-view></router-view>
  <h1 v-text="pagetitle"></h1>
  How can I change the page title???
</div>

回答by Ru Chern Chong

In your <h1></h1>tag, just use the following

在您的<h1></h1>标签中,只需使用以下内容

{{ $route.meta.title }}

回答by Nick Kos

If you would like to have correct browser history use this one:

如果您想拥有正确的浏览器历史记录,请使用以下命令:

router.afterEach((to, from) => {
  Vue.nextTick( () => {
    document.title = to.meta.title ? to.meta.title : 'default title';
  });
})

回答by Benjamin Arthuys

Also if you need to change the document's title-tag, in your router.beforeEachreplace this line :

此外,如果您需要更改文档的标题标签,请在router.beforeEach替换此行中:

this.$emit('pagetitle', to.meta.title);

this.$emit('pagetitle', to.meta.title);

with

document.title = to.meta.title;

document.title = to.meta.title;

It will work.

它会起作用。