vue-meta


vue-meta讓你更優雅的管理頭部標簽

5

在 Vue SPA 應用中,如果想要修改HTML的頭部標簽,或許,你會在代碼里,直接這么做:

// 改下title document.title = 'what?' // 引入一段script let s = document.createElement('script') s.setAttribute('src', './vconsole.js') document.head.appendChild(s) // 修改meta信息,或者給html標簽添加屬性... // 此處省略一大坨代碼...

今天給大家介紹一種更優雅的方式,去管理頭部標簽 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有以下特點:

  • 在組件內設置 metaInfo,便可輕松實現頭部標簽的管理
  • metaInfo 的數據都是響應的,如果數據變化,頭部信息會自動更新
  • 支持 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'] }, ... }

可以看一下頁面顯示

clipboard.png

熟悉 Nuxt.js 的同學,會發現配置 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 的使用方法,或許大家會想這些功能是怎么實現的,那下面就和大家分享一下源碼。

怎么區分 client 和 server渲染?

vue-meta 會在 beforeCreate() 鈎子函數中,將組件中設置的 metaInfo ,放在 this.metaInfothis.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等生命周期的鈎子函數中,監聽 $metaInfo 的變化,如果發生改變,就調用 $meta 下的 refresh方法。這也是 metaInfo 做到響應的原因。

created () {
  if (!this.$isServer && this.$metaInfo) { this.$watch('$metaInfo', () => { batchID = batchUpdate(batchID, () => this.$meta().refresh()) }) } },

Server端,主要是暴露 $meta 下的 inject 方法,調用 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 默認會對特殊字符串進行轉義,如果設置了 __dangerouslyDisableSanitizers,就不會對再做轉義處理。

const escapeHTML = (str) => typeof window === 'undefined' // server-side escape sequence ? String(str) .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#x27;') // 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實戰 和 Nuxt.js踩坑分享。文中有任何表述不清或不當的地方,歡迎大家批評指正。
給大家推薦我們的公眾號 前端新視野 ,一個很認真的日刊公眾號,歡迎掃描下方二維碼關注!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM