詳解vue-meta如何讓你更優(yōu)雅的管理頭部標簽
在 Vue SPA 應用中,如果想要修改HTML的頭部標簽,或許,你會在代碼里,直接這么做:
// 改下title
document.title = 'what?'
// 引入一段script
let s = document.createElement('script')
s.setAttribute('src', './vconsole.js')
document.head.appendChild(s)
// 修改meta信息,或者給html標簽添加屬性...
// 此處省略一大坨代碼...
今天給大家介紹一種更優(yōu)雅的方式,去管理頭部標簽 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頭部標簽,同時也支持SSR。
vue-meta有以下特點:
- 在組件內(nèi)設置 metaInfo,便可輕松實現(xiàn)頭部標簽的管理
- metaInfo 的數(shù)據(jù)都是響應的,如果數(shù)據(jù)變化,頭部信息會自動更新
- 支持 SSR
如何使用
在介紹如何使用之前,先和大家普及一個最近很火的名詞 服務端渲染(SSR, Server Side Render),簡單來講,就是在訪問某個頁面時,服務端會把渲染好的頁面,直接返回給瀏覽器。
我們知道 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: '標題'
}
},
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 的同學,會發(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
})
更加全面詳細的api,可以參考vue-meta github
Server 服務端
Step 1. 將 $meta 對象注入到上下文中
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 方法,用在服務端,返回設置的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 的使用方法,或許大家會想這些功能是怎么實現(xiàn)的,那下面就和大家分享一下源碼。
怎么區(qū)分 client 和 server渲染?
vue-meta 會在 beforeCreate() 鉤子函數(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 會在created等生命周期的鉤子函數(shù)中,監(jiān)聽 $metaInfo 的變化,如果發(fā)生改變,就調(diào)用 $meta 下的 refresh 方法。這也是 metaInfo 做到響應的原因。
created () {
if (!this.$isServer && this.$metaInfo) {
this.$watch('$metaInfo', () => {
batchID = batchUpdate(batchID, () => this.$meta().refresh())
})
}
},
Server端,主要是暴露 $meta 下的 inject 方法,調(diào)用 inject 方法,會返回對應的信息。
client 和 server端 是如何修改標簽的?
client端 修改標簽,就是本文開頭提到的 通過原生js,直接修改
return function updateTitle (title = document.title) {
document.title = title
}
server端,就是通過 text方法,返回string格式的標簽
return function titleGenerator (type, data) {
return {
text () {
return `<${type} ${attribute}="true">${data}</${type}>`
}
}
}
__dangerouslyDisableSanitizers 做了什么?
vue-meta 默認會對特殊字符串進行轉(zhuǎn)義,如果設置了 __dangerouslyDisableSanitizers,就不會對再做轉(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實戰(zhàn) 和 Nuxt.js踩坑分享。文中有任何表述不清或不當?shù)牡胤?,歡迎大家批評指正。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用vuetify實現(xiàn)全局v-alert消息通知的方法
使用強大的Vuetify開發(fā)前端頁面,結(jié)果發(fā)現(xiàn)官方?jīng)]有提供簡便的全局消息通知組件,所以自己動手寫了一個簡單的組件,接下來通過本文給大家介紹使用vuetify實現(xiàn)全局v-alert消息通知的詳細代碼,感興趣的朋友跟隨小編一起看看吧2024-02-02
基于vue v-for 循環(huán)復選框-默認勾選第一個的實現(xiàn)方法
下面小編就為大家分享一篇基于vue v-for 循環(huán)復選框-默認勾選第一個的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03
vue2 mint-ui loadmore實現(xiàn)下拉刷新,上拉更多功能
這篇文章主要介紹了vue2 mint-ui loadmore實現(xiàn)下拉刷新,上拉更多功能,需要的朋友可以參考下2018-03-03

