路由 mate 元信息处理
这一节就是对我们的标题进行优化!
- 首先进入路由中给每个路由填写基本的 mate 信息
let title = 'Airbnb爱彼迎 - 全球民宿_公寓_短租_住宿_预订平台'
let keywords = 'Airbnb,bnb,爱彼迎,爱彼迎官网,民宿,民宿预订平台,名宿,酒店预定,公寓,短租,住宿'
let description = 'Airbnb爱彼迎是全球民宿短租公寓预订平台,全球百万特色民宿、短租、酒店、公寓、客栈房源,价格优惠,更有树屋、海景别墅、花园洋房等多种特色住宿预订供您选择'
const routes = [
{
path: '/login',
name: 'login',
component: () => import('@/views/login/index.vue'),
meta: {
title: 'Airbnb爱彼迎 - 登录注册',
keywords: '',
description: '',
keepAlive: false
}
},
{
path: '/home',
name: 'home',
component: () => import('@/views/home/index.vue'),
meta: {
title,
keywords,
description,
keepAlive: false
}
},
{
path: '/detail/:id/:title',
name: 'detail',
component: () => import('@/views/detail/index.vue'),
meta: {
title: 'Airbnb爱彼迎 - ',
keywords: '',
description: '',
keepAlive: false
}
},
]
- 然后在 index.html 里面填写占位
<title></title>
<meta name="keywords" content="" />
<meta name="description" content="" />
- 服务端渲染标题:进入
server.js
// 获取路由中的元信息(服务端渲染时改变标题)
const { meta } = state.route
const { title, keywords, description } = meta
// 5. 注入渲染后的应用程序 HTML 到模板占位符中(重点!)
const html = template.replace(`<!--ssr-outlet-->`, appHtml)
.replace('\'<!--vuex-state-->\'', JSON.stringify(state))
.replace('<title>', `<title>${title}`)
.replace('<meta name="keywords" content="" />', `<meta name="keywords" content="${keywords}" />`)
.replace('<meta name="description" content="" />', `<meta name="description" content="${description}" />`)
- 客户端渲染标题(重点):进入
entry-client.ts
// 新增一个路由后置守卫
router.afterEach((to, from, next) => {
// 填充 mate 元信息
const { title, keywords, description } = to.meta
// 详情页标题
const detailTitle = to.params?.title
if (detailTitle) {
document.title = title ? `${title}${detailTitle}` : ''
} else {
document.title = title ? `${title}` : ''
}
const keywordsMeta = document.querySelector('meta[name="keywords"]')
keywordsMeta?.setAttribute("content", `${keywords}`)
const descriptionMeta = document.querySelector('meta[name="description"]')
descriptionMeta?.setAttribute("content", `${description}`)
})
到这里我们就实现了路由页面标题等信息的填写,利于 SEO