詳解vue-meta如何讓你更優(yōu)雅的管理頭部標(biāo)簽
在 Vue SPA 應(yīng)用中,如果想要修改HTML的頭部標(biāo)簽,或許,你會(huì)在代碼里,直接這么做:
// 改下title
document.title = 'what?'
// 引入一段script
let s = document.createElement('script')
s.setAttribute('src', './vconsole.js')
document.head.appendChild(s)
// 修改meta信息,或者給html標(biāo)簽添加屬性...
// 此處省略一大坨代碼...
今天給大家介紹一種更優(yōu)雅的方式,去管理頭部標(biāo)簽 vue-meta
vue-meta介紹
Manage page meta info in Vue 2.0 components. SSR + Streaming supported. Inspired by react-helmet.
借用vue-meta github 上的介紹,基于Vue 2.0 的 vue-meta 插件,主要用于管理HMTL頭部標(biāo)簽,同時(shí)也支持SSR。
vue-meta有以下特點(diǎn):
- 在組件內(nèi)設(shè)置 metaInfo,便可輕松實(shí)現(xiàn)頭部標(biāo)簽的管理
- metaInfo 的數(shù)據(jù)都是響應(yīng)的,如果數(shù)據(jù)變化,頭部信息會(huì)自動(dòng)更新
- 支持 SSR
如何使用
在介紹如何使用之前,先和大家普及一個(gè)最近很火的名詞 服務(wù)端渲染(SSR, Server Side Render),簡(jiǎn)單來講,就是在訪問某個(gè)頁面時(shí),服務(wù)端會(huì)把渲染好的頁面,直接返回給瀏覽器。
我們知道 vue-meta 是支持SSR的,下面的介紹分成兩部分:
Client 客戶端
在入口文件中,install vue-meta plugin
import Vue from 'vue'
import VueRouter from 'vue-router'
import VueMeta from 'vue-meta'
Vue.use(VueRouter)
Vue.use(VueMeta)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
})
然后就可以在組件中使用了
export default {
data () {
return {
myTitle: '標(biāo)題'
}
},
metaInfo: {
title: this.myTitle,
titleTemplate: '%s - by vue-meta',
htmlAttrs: {
lang: 'zh'
},
script: [{innerHTML: 'console.log("hello hello!")', type: 'text/javascript'}],
__dangerouslyDisableSanitizers: ['script']
},
...
}
可以看一下頁面顯示

熟悉 Nuxt.js 的同學(xué),會(huì)發(fā)現(xiàn)配置 meta info 的 keyName 不一致??梢酝ㄟ^下面的配置方法來修改:
// vue-meta configuration
Vue.use(Meta, {
keyName: 'head', // the component option name that vue-meta looks for meta info on.
attribute: 'data-n-head', // the attribute name vue-meta adds to the tags it observes
ssrAttribute: 'data-n-head-ssr', // the attribute name that lets vue-meta know that meta info has already been server-rendered
tagIDKeyName: 'hid' // the property name that vue-meta uses to determine whether to overwrite or append a tag
})
更加全面詳細(xì)的api,可以參考vue-meta github
Server 服務(wù)端
Step 1. 將 $meta 對(duì)象注入到上下文中
server-entry.js:
import app from './app'
const router = app.$router
const meta = app.$meta() // here
export default (context) => {
router.push(context.url)
context.meta = meta // and here
return app
}
$meta 主要提供了,inject 和 refresh 方法。inject 方法,用在服務(wù)端,返回設(shè)置的metaInfo ;refresh 方法,用在客戶端,作用是更新meta信息。
Step 2. 使用 inject() 方法 輸出頁面
server.js:
app.get('*', (req, res) => {
const context = { url: req.url }
renderer.renderToString(context, (error, html) => {
if (error) return res.send(error.stack)
const bodyOpt = { body: true }
const {
title, htmlAttrs, bodyAttrs, link, style, script, noscript, meta
} = context.meta.inject()
return res.send(`
<!doctype html>
<html data-vue-meta-server-rendered ${htmlAttrs.text()}>
<head>
${meta.text()}
${title.text()}
${link.text()}
${style.text()}
${script.text()}
${noscript.text()}
</head>
<body ${bodyAttrs.text()}>
${html}
<script src="/assets/vendor.bundle.js"></script>
<script src="/assets/client.bundle.js"></script>
${script.text(bodyOpt)}
</body>
</html>
`)
})
})
源碼分析
前面說了 vue-meta 的使用方法,或許大家會(huì)想這些功能是怎么實(shí)現(xiàn)的,那下面就和大家分享一下源碼。
怎么區(qū)分 client 和 server渲染?
vue-meta 會(huì)在 beforeCreate() 鉤子函數(shù)中,將組件中設(shè)置的 metaInfo ,放在 this.$metaInfo 中。我們可以在其他生命周期中,訪問 this.$metaInfo 下的屬性。
if (typeof this.$options[options.keyName] === 'function') {
if (typeof this.$options.computed === 'undefined') {
this.$options.computed = {}
}
this.$options.computed.$metaInfo = this.$options[options.keyName]
}
vue-meta 會(huì)在created等生命周期的鉤子函數(shù)中,監(jiān)聽 $metaInfo 的變化,如果發(fā)生改變,就調(diào)用 $meta 下的 refresh 方法。這也是 metaInfo 做到響應(yīng)的原因。
created () {
if (!this.$isServer && this.$metaInfo) {
this.$watch('$metaInfo', () => {
batchID = batchUpdate(batchID, () => this.$meta().refresh())
})
}
},
Server端,主要是暴露 $meta 下的 inject 方法,調(diào)用 inject 方法,會(huì)返回對(duì)應(yīng)的信息。
client 和 server端 是如何修改標(biāo)簽的?
client端 修改標(biāo)簽,就是本文開頭提到的 通過原生js,直接修改
return function updateTitle (title = document.title) {
document.title = title
}
server端,就是通過 text方法,返回string格式的標(biāo)簽
return function titleGenerator (type, data) {
return {
text () {
return `<${type} ${attribute}="true">${data}</${type}>`
}
}
}
__dangerouslyDisableSanitizers 做了什么?
vue-meta 默認(rèn)會(huì)對(duì)特殊字符串進(jìn)行轉(zhuǎn)義,如果設(shè)置了 __dangerouslyDisableSanitizers,就不會(huì)對(duì)再做轉(zhuǎn)義處理。
const escapeHTML = (str) => typeof window === 'undefined' // server-side escape sequence ? String(str) .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, ''') // client-side escape sequence : String(str) .replace(/&/g, '\u0026') .replace(/</g, '\u003c') .replace(/>/g, '\u003e') .replace(/"/g, '\u0022') .replace(/'/g, '\u0027')
最后
最開始接觸 vue-meta 是在 Nuxt.js 中。如果想了解 Nuxt.js,歡迎大家閱讀Nuxt.js實(shí)戰(zhàn) 和 Nuxt.js踩坑分享。文中有任何表述不清或不當(dāng)?shù)牡胤?,歡迎大家批評(píng)指正。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Vue觸發(fā)input選取文件點(diǎn)擊事件操作
這篇文章主要介紹了Vue觸發(fā)input選取文件點(diǎn)擊事件操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-08-08
Vue3嵌套路由中使用keep-alive緩存多層的實(shí)現(xiàn)
本文介紹了Vue3 嵌套路由中使用?keep-alive緩存多層的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04
vue?element-ui的table列表中展示多張圖片(可放大)效果實(shí)例
這篇文章主要給大家介紹了關(guān)于vue?element-ui的table列表中展示多張圖片(可放大)效果的相關(guān)資料,文中通過代碼示例介紹的非常詳細(xì),需要的朋友可以參考下2023-08-08
如何用webpack4帶你實(shí)現(xiàn)一個(gè)vue的打包的項(xiàng)目
這篇文章主要介紹了如何用webpack4帶你實(shí)現(xiàn)一個(gè)vue的打包的項(xiàng)目,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-06-06
electron-vue利用webpack打包實(shí)現(xiàn)多頁面的入口文件問題
項(xiàng)目需要在electron的項(xiàng)目中新打開一個(gè)窗口,利用webpack作為靜態(tài)資源打包器,發(fā)現(xiàn)在webpack中可以設(shè)置多頁面的入口,今天來講一下我在electron中利用webpack建立多頁面入口的踩坑經(jīng)驗(yàn),需要的朋友可以參考下2019-05-05

