Home Web Front-end JS Tutorial How to manage head tags using vue-meta

How to manage head tags using vue-meta

Jun 11, 2018 pm 03:33 PM
vue

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use echarts in vue How to use echarts in vue May 09, 2024 pm 04:24 PM

Using ECharts in Vue makes it easy to add data visualization capabilities to your application. Specific steps include: installing ECharts and Vue ECharts packages, introducing ECharts, creating chart components, configuring options, using chart components, making charts responsive to Vue data, adding interactive features, and using advanced usage.

The role of export default in vue The role of export default in vue May 09, 2024 pm 06:48 PM

Question: What is the role of export default in Vue? Detailed description: export default defines the default export of the component. When importing, components are automatically imported. Simplify the import process, improve clarity and prevent conflicts. Commonly used for exporting individual components, using both named and default exports, and registering global components.

How to use map function in vue How to use map function in vue May 09, 2024 pm 06:54 PM

The Vue.js map function is a built-in higher-order function that creates a new array where each element is the transformed result of each element in the original array. The syntax is map(callbackFn), where callbackFn receives each element in the array as the first argument, optionally the index as the second argument, and returns a value. The map function does not change the original array.

The difference between event and $event in vue The difference between event and $event in vue May 08, 2024 pm 04:42 PM

In Vue.js, event is a native JavaScript event triggered by the browser, while $event is a Vue-specific abstract event object used in Vue components. It is generally more convenient to use $event because it is formatted and enhanced to support data binding. Use event when you need to access specific functionality of the native event object.

The difference between export and export default in vue The difference between export and export default in vue May 08, 2024 pm 05:27 PM

There are two ways to export modules in Vue.js: export and export default. export is used to export named entities and requires the use of curly braces; export default is used to export default entities and does not require curly braces. When importing, entities exported by export need to use their names, while entities exported by export default can be used implicitly. It is recommended to use export default for modules that need to be imported multiple times, and use export for modules that are only exported once.

The role of onmounted in vue The role of onmounted in vue May 09, 2024 pm 02:51 PM

onMounted is a component mounting life cycle hook in Vue. Its function is to perform initialization operations after the component is mounted to the DOM, such as obtaining references to DOM elements, setting data, sending HTTP requests, registering event listeners, etc. It is only called once when the component is mounted. If you need to perform operations after the component is updated or before it is destroyed, you can use other lifecycle hooks.

What are hooks in vue What are hooks in vue May 09, 2024 pm 06:33 PM

Vue hooks are callback functions that perform actions on specific events or lifecycle stages. They include life cycle hooks (such as beforeCreate, mounted, beforeDestroy), event handling hooks (such as click, input, keydown) and custom hooks. Hooks enhance component control, respond to component life cycles, handle user interactions and improve component reusability. To use hooks, just define the hook function, execute the logic and return an optional value.

What scenarios can event modifiers in vue be used for? What scenarios can event modifiers in vue be used for? May 09, 2024 pm 02:33 PM

Vue.js event modifiers are used to add specific behaviors, including: preventing default behavior (.prevent) stopping event bubbling (.stop) one-time event (.once) capturing event (.capture) passive event listening (.passive) Adaptive modifier (.self)Key modifier (.key)

See all articles