«

vue中设置网页标题

时间:2023-5-28 11:04     作者:小诸葛     分类: Vue     正在检查是否收录...


1.在项目根目录中的 vue.config.js 文件中设置 title 字段,代码如下:

// vue.config.js
module.exports = {
  pages: {
    index: {
      entry: 'src/main.js',
      title: 'My App' //在这里修改应用程序的标题
    }
  }
}

在上面的示例代码中,我们将 title 字段设置为 "My App"。此时,如果您在浏览器中打开应用程序,将会看到浏览器标签页中显示的标题是 "My App"。
如果您希望在不同页面中显示不同的标题,可以使用 vue-router 提供的 meta 属性。例如:

// router.js
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home,
      meta: {
        title: '首页' // 修改页面标题
      }
    },
    //...其他路由省略
  ]
})

router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title
  } else {
    document.title = 'My App' // 默认标题
  }
  next()
})

export default router

在上述代码中,我们在路由配置中添加了 meta 属性,并在 beforeEach 钩子函数中设置了页面的标题,这样就可以为不同的页面设置不同的标题了。

需要注意的是,由于在浏览器中,document.title 是全局变量,因此最好在每次切换路由时都设置一次标题,以确保应用程序的标题在每个页面上都正确显示。

vue

推荐阅读:


扫描二维码,在手机上阅读