1. 在 router/index.js 中,使用meta属性的title设置好每个路由对应的title值

/* router/index.js: */
 
const routes = [
 {
    path: '/home/search',
    name: 'search',
    component: search,
	meta: {
		title: '首页'
	}
  }]

2.在 main.js 中设置路由守卫,vue页面切换时,网页title随之切换

/* main.js: */
 
new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

router.beforeEach((to, from, next) => {
  /* 路由发生变化修改页面title */
  if (to.meta.title) {
    document.title = to.meta.title
  }
  next()
})

设置好之后,路由就生效了,但是很多兄弟遇到了这么一个问题:刷新页面之后title失效了

原因

查询 vue-router1.0 的说明文档,文档上的 Basic Usage 代码如下:

// Load the plugin
Vue.use(VueRouter)

// Define some components
var Foo = {
    template: '<p>This is foo!</p>'
}

var Bar = {
    template: '<p>This is bar!</p>'
}

// The router needs a root component to render.
// For demo purposes, we will just use an empty one
// because we are using the HTML as the app template.
// !! Note that the App is not a Vue instance.
var App = {}

// Create a router instance.
// You can pass in additional options here, but let's
// keep it simple for now.
var router = new VueRouter()

// Define some routes.
// Each route should map to a component. The "component" can
// either be an actual component constructor created via
// Vue.extend(), or just a component options object.
// We'll talk about nested routes later.
router.map({
    '/foo': {
        component: Foo
    },
    '/bar': {
        component: Bar
    }
})

// Now we can start the app!
// The router will create an instance of App and mount to
// the element matching the selector #app.
router.start(App, '#app')

可以发现,样例中把 router.start(App, '#app') 这行代码放在了最后。因为这一步是创建和挂载根实例,是启动路由的最后一步,需要在定义路由实例和配置路由之后进行。

 

解决:

在使用 vue-router 模块时,挂载根实例的步骤要放在最后,不然会导致配置不成功。

也就是第二步

router.beforeEach((to, from, next) => {
  /* 路由发生变化修改页面title */
  if (to.meta.title) {
    document.title = to.meta.title
  }
  next()
})

-------这里一定要放在最后面就可以了-------------

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

或者

router.start(App, '#app')

 

Logo

前往低代码交流专区

更多推荐