Describes how vue-meta allows you to manage header tags more elegantly, and describes vue-meta
In the Vue SPA application, if you want to modify the HTML header tag, you may directly do this in the Code:
// Change titledocument. title = 'What? '// Introduce a piece of scriptlet s = document. createElement ('script') s. setAttribute ('src ','. /vconsole. js') document. head. appendChild (s) // modify meta information, or add attributes to html tags... // a large batch of code is omitted here...
Today, we will introduce you to a more elegant way to manage the head tag vue-meta.
Vue-meta
Manage page meta info in Vue 2.0 components. SSR + Streaming supported. supported Red by react-helmet.
Based on vue-meta github, the Vue-meta plug-in based on vue 2.0 is mainly used to manage HMTL header tags and supports SSR.
Vue-meta has the following features:
- You can easily manage header labels by setting metaInfo in the component.
- The metaInfo data is responsive. If the data changes, the header information is automatically updated.
- Support for SSR
How to Use
Before introducing how to use it, I would like to popularize a recently popular term Server rendering (SSR, Server Side Render). Simply put, when accessing a page, the server directly returns the rendered page to the browser.
We know that vue-meta supports SSR. The following introduction is divided into two parts:
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: '<App/>', components: { App }})
Then you can use it in the component.
Export default {data () {return {myTitle: 'title'}, metaInfo: {title: this. myTitle, titleTemplate: '% s-by vue-meta', htmlAttrs: {lang: 'zh'}, script: [{innerHTML: 'console. log ("hello! ") ', Type: 'text/javascript'}], _ dangerouslyDisableSanitizers: ['script']},...}
You can check the page.
If you are familiar with Nuxt. js, you will find that the keynames configured for meta info are inconsistent. You can modify the configuration as follows:
// 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})
For more comprehensive and detailed APIs, refer to vue-meta github.
Server
Step 1. inject $ meta object into context
Server-entry.js:
import app from './app'const router = app.$routerconst meta = app.$meta() // hereexport default (context) => { router.push(context.url) context.meta = meta // and here return app}
$ Meta mainly provides the inject and refresh methods. The inject method is used on the server and the metaInfo and refresh methods are returned. It is used on the client to update meta information.
Step 2. Use the inject () method to output the page
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>
Source code analysis
We have discussed how to use vue-meta. Maybe you will think about how these functions are implemented. Let's share the source code with you.
How to distinguish between client and server rendering?
Vue-meta stores the metaInfo set in the component in the beforeCreate () Hook Function in this. $ metaInfo. We can access the attributes under this. $ metaInfo in other lifecycles.
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 listens to $ metaInfo changes in the hook function of the created and other lifecycles. If it changes, call the refresh method under $ meta. This is why metaInfo responds.
created () { if (!this.$isServer && this.$metaInfo) { this.$watch('$metaInfo', () => { batchID = batchUpdate(batchID, () => this.$meta().refresh()) }) }},
The Server exposes the inject method under $ meta. When the inject method is called, the corresponding information is returned.
How does the client and server modify tags?
The client side modifies labels directly through Native js as mentioned at the beginning of this article.
return function updateTitle (title = document.title) { document.title = title}
The server returns a string-format tag using the text method.
return function titleGenerator (type, data) { return { text () { return `<${type} ${attribute}="true">${data}</${type}>` } }}
_ What did dangerouslyDisableSanitizers do?
By default, vue-meta will escape special strings. If _ dangerouslyDisableSanitizers is set, no escape processing will be performed.
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')
Last
Vue-meta was first introduced in Nuxt. js. If you want to know about Nuxt. js, you are welcome to read the Nuxt. js practice and the Nuxt. js step-by-step sharing. We welcome your criticism for any unclear or improper expression in this article.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.