溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

在Vue SPA應(yīng)用中修改HTML頭部標(biāo)簽的方法

發(fā)布時間:2021-02-20 11:00:00 來源:億速云 閱讀:497 作者:小新 欄目:web開發(fā)

這篇文章主要介紹在Vue SPA應(yīng)用中修改HTML頭部標(biāo)簽的方法,文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!

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

// 改下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)簽,同時也支持SSR。

vue-meta有以下特點:

  1. 在組件內(nèi)設(shè)置 metaInfo,便可輕松實現(xiàn)頭部標(biāo)簽的管理

  2. metaInfo 的數(shù)據(jù)都是響應(yīng)的,如果數(shù)據(jù)變化,頭部信息會自動更新

  3. 支持 SSR

如何使用

在介紹如何使用之前,先和大家普及一個最近很火的名詞 服務(wù)端渲染(SSR, Server Side Render),簡單來講,就是在訪問某個頁面時,服務(wù)端會把渲染好的頁面,直接返回給瀏覽器。

我們知道 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']
 },
 ...
}

可以看一下頁面顯示

在Vue SPA應(yīng)用中修改HTML頭部標(biāo)簽的方法

熟悉 Nuxt.js 的同學(xué),會發(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 對象注入到上下文中

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 的使用方法,或許大家會想這些功能是怎么實現(xiàn)的,那下面就和大家分享一下源碼。

怎么區(qū)分 client 和 server渲染?

vue-meta 會在 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 會在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 方法,會返回對應(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)會對特殊字符串進(jìn)行轉(zhuǎn)義,如果設(shè)置了 __dangerouslyDisableSanitizers,就不會對再做轉(zhuǎn)義處理。

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實戰(zhàn) 和 Nuxt.js踩坑分享。文中有任何表述不清或不當(dāng)?shù)牡胤?,歡迎大家批評指正。

以上是“在Vue SPA應(yīng)用中修改HTML頭部標(biāo)簽的方法”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI