頁面的meta設(shè)置對于SEO的設(shè)置非常重要,比如你現(xiàn)在要作個(gè)新聞頁面膛薛,那為了搜索引擎對新聞的收錄听隐,需要每個(gè)頁面對新聞都有不同的title和meta設(shè)置。
首先了解nuxt下設(shè)置meta的方法
- 借助 head 屬性哄啄,Nuxt.js 可以在 nuxt.config.js 中配置應(yīng)用的 meta 信息雅任。
module.exports = {
/*
** Headers of the page
*/
head: {
title: '前端小喵', // 網(wǎng)站標(biāo)題
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '此處是網(wǎng)站描述' },
{ hid: 'keywords', name: 'keywords', content: '此處是網(wǎng)站關(guān)鍵詞' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
}
}
- 組件中Nuxt.js 使用了
vue-meta
更新應(yīng)用的頭部標(biāo)簽(Head)
和html 屬性
风范。
head(){
return{
title: `前端小喵`,
meta:[
{hid:'description',name:'description',content: '前端小喵'},
{hid:'keywords',name:'keywords',content: '前端小喵'}
]
}
}
動態(tài)設(shè)置meta信息
下面以一個(gè)新聞詳情的meta信息設(shè)置為例:
首先從列表傳參到詳情頁面獲取meta信息,然后再通過this綁定到頁面上沪么。
/new頁面,傳id參數(shù)到new-id頁面
來點(diǎn)假數(shù)據(jù)吧
list: [
{
id: '1',
title: '前端小喵'
},
{
id: '2',
title: '前端小喵'
}
]
<li v-for="(item, index) in list" :key="'list_'+item.id">
<nuxt-link :to="`/new/${item.id}`" :title="item.title">
{{item.title}}
</nuxt-link>
</li>
...
詳情頁面接收參數(shù)硼婿,從后臺接口獲取關(guān)鍵詞,描述禽车,標(biāo)題
來點(diǎn)假數(shù)據(jù)吧
{
"code":0,
"message":"success",
"data":{
"id":1,
"title":"前端小喵",
"keywords": "前端小喵",
"description": "前端小喵"
}
}
async asyncData({ store, params, error, req, query }) {
try {
const isServer = process.server
const token = isServer ? req.cookies[TokenKey] : getToken()
let { id } = params
let par = {
id: id
}
let [detialRes,] = await Promise.all([
user_api_send('/api/***********', par, 'post', token),
])
return {
detial: detialRes.data
}
} catch(err) {
console.log(err)
}
},
data() {
return {
detial: {
}
}
}
設(shè)置head
head(){
return{
title: `前端小喵-${this.detial.title}`,
meta:[
{hid:'description',name:'description',content: this.detial.description || '前端小喵'},
{hid:'keywords',name:'keywords',content: this.detial.keywords || '前端小喵'}
]
}
}
這樣就設(shè)置完成了寇漫。