Home > Web Front-end > JS Tutorial > body text

How to manage head tags using vue-meta

亚连
Release: 2018-06-11 15:33:52
Original
4468 people have browsed it

This article mainly introduces in detail how vue-meta allows you to manage header tags more elegantly. Now I share it with you and give it as a reference.

In the Vue SPA application, if you want to modify the HTML head tag, you may do so directly in the code:

// 改下title
document.title = 'what?'
// 引入一段script
let s = document.createElement('script')
s.setAttribute('src', './vconsole.js')
document.head.appendChild(s)
// 修改meta信息,或者给html标签添加属性...
// 此处省略一大坨代码...
Copy after login

Today I will introduce to you a more elegant method way to manage the header tag vue-meta

vue-meta introduction

Manage page meta info in Vue 2.0 components. SSR Streaming supported. Inspired by react-helmet .

Borrowing from the introduction on vue-meta github, the vue-meta plug-in based on Vue 2.0 is mainly used to manage HMTL header tags and also supports SSR.

vue-meta has the following characteristics:

  1. Set metaInfo in the component to easily manage the header tags

  2. metaInfo data is all responsive. If the data changes, the header information will be automatically updated

  3. Support SSR

How to use

Before introducing how to use it, let me popularize a recently popular term server side rendering (SSR, Server Side Render). Simply put, it is when visiting When a certain page is reached, the server will return the rendered page directly to the browser.

We know that vue-meta supports SSR. The following introduction is divided into two parts:

Client client

In the entry file, 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: &#39;<App/>&#39;,
 components: { App }
})
Copy after login

Then you can use it in the component

export default {
 data () {
  return {
   myTitle: &#39;标题&#39;
  }
 },
 metaInfo: {
  title: this.myTitle,
  titleTemplate: &#39;%s - by vue-meta&#39;,
  htmlAttrs: {
   lang: &#39;zh&#39;
  },
  script: [{innerHTML: &#39;console.log("hello hello!")&#39;, type: &#39;text/javascript&#39;}],
  __dangerouslyDisableSanitizers: [&#39;script&#39;]
 },
 ...
}
Copy after login

You can take a look at the page display

Be familiar with Nuxt.js Students will find that the keyName of the meta info configuration is inconsistent. It can be modified through the following configuration method:

// vue-meta configuration 
Vue.use(Meta, {
 keyName: &#39;head&#39;, // the component option name that vue-meta looks for meta info on.
 attribute: &#39;data-n-head&#39;, // the attribute name vue-meta adds to the tags it observes
 ssrAttribute: &#39;data-n-head-ssr&#39;, // the attribute name that lets vue-meta know that meta info has already been server-rendered
 tagIDKeyName: &#39;hid&#39; // the property name that vue-meta uses to determine whether to overwrite or append a tag
})
Copy after login

For more comprehensive and detailed API, please refer to vue-meta github

Server server

Step 1. Inject the $meta object into the context

server-entry.js:

import app from &#39;./app&#39;

const router = app.$router
const meta = app.$meta() // here

export default (context) => {
 router.push(context.url)
 context.meta = meta // and here
 return app
}
Copy after login

$meta mainly provides the inject and refresh methods. The inject method, used on the server side, returns the set metaInfo; the refresh method, used on the client side, is used to update meta information.

Step 2. Use the inject() method to output the page

server.js:

app.get(&#39;*&#39;, (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>
  `)
 })
})
Copy after login

Source code analysis

I mentioned how to use vue-meta earlier. Maybe you will wonder how these functions are implemented, so let me share the source code with you.

How to distinguish client and server rendering?

vue-meta will put the metaInfo set in the component in this.$metaInfo in the beforeCreate() hook function. We can access the properties under this.$metaInfo in other life cycles.

if (typeof this.$options[options.keyName] === &#39;function&#39;) {
 if (typeof this.$options.computed === &#39;undefined&#39;) {
  this.$options.computed = {}
 }
 this.$options.computed.$metaInfo = this.$options[options.keyName]
}
Copy after login

vue-meta will monitor changes in $metaInfo in the hook functions of the life cycle such as created. If changes occur, the refresh method under $meta will be called. This is why metaInfo is responsive.

created () {
 if (!this.$isServer && this.$metaInfo) {
  this.$watch(&#39;$metaInfo&#39;, () => {
   batchID = batchUpdate(batchID, () => this.$meta().refresh())
  })
 }
},
Copy after login

Server side mainly exposes the inject method under $meta. Calling the inject method will return the corresponding information.

How do the client and server modify the tag?

Modifying tags on the client side means directly modifying

return function updateTitle (title = document.title) {
 document.title = title
}
Copy after login

on the server side through the native js mentioned at the beginning of this article. It uses the text method to return tags in string format

return function titleGenerator (type, data) {
 return {
  text () {
   return `<${type} ${attribute}="true">${data}</${type}>`
  }
 }
}
Copy after login

__dangerouslyDisableSanitizers What do they do?

vue-meta will escape special strings by default. If __dangerouslyDisableSanitizers is set, it will not be escaped.

const escapeHTML = (str) => typeof window === &#39;undefined&#39;
 // server-side escape sequence
 ? String(str)
  .replace(/&/g, &#39;&&#39;)
  .replace(/</g, &#39;<&#39;)
  .replace(/>/g, &#39;>&#39;)
  .replace(/"/g, &#39;"&#39;)
  .replace(/&#39;/g, &#39;&#39;&#39;)
 // client-side escape sequence
 : String(str)
  .replace(/&/g, &#39;\u0026&#39;)
  .replace(/</g, &#39;\u003c&#39;)
  .replace(/>/g, &#39;\u003e&#39;)
  .replace(/"/g, &#39;\u0022&#39;)
  .replace(/&#39;/g, &#39;\u0027&#39;)
Copy after login

Finally

The first time I came into contact with vue-meta was in Nuxt.js. If you want to learn about Nuxt.js, you are welcome to read Nuxt.js Practical Practice and Nuxt.js Pitfall Sharing. If there is any unclear or inappropriate expression in the article, you are welcome to criticize and correct it.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Using icon icons through Element in Vue

How to use Vue.set() to achieve dynamic data response

How to dynamically bind images and data return image paths in vue

How to dynamically change static images and request network images in vue

Preloading watch usage in vue

How to use the browser plug-in Batarang in Angular

How to implement the pasteboard copy function using JS

Number type in JS (detailed tutorial)

The above is the detailed content of How to manage head tags using vue-meta. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
vue
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template