Open dailynodejs opened 2 years ago
什么是vue-meta?
what?使用 Vue 的内置响应性来管理应用程序的元数据
how?只需将特殊属性 metaInfo
添加到任何或所有组件,因为这些将自动自上而下合并
so?嵌套组件可以覆盖彼此的值,让您可以在需要的时间和地点轻松添加或删除元数据!
简单使用
安装
npm i vue-meta
入口文件配置
import Vue from 'vue'
import VueMeta from 'vue-meta'
Vue.use(VueMeta)
配置参数选项 https://vue-meta.nuxtjs.org/api/#plugin-options https://vue-meta.nuxtjs.org/api/#metainfo-properties
// 全局配置插件信息 Plugin Options
Vue.use(Meta, {
keyName: 'metaInfo',
attribute: 'data-vue-meta',
ssrAttribute: 'data-vue-meta-server-rendered',
tagIDKeyName: 'vmid',
refreshOnceOnNavigation: true
})
// 页面内配置meta元信息 Meta properties
<template>
<div id="page">
<h1>Home Page</h1>
</div>
</template>
<script>
export default {
name: 'Home',
metaInfo: {
title: 'My Awesome Webapp',
// override the parent template and just use the above title only
titleTemplate: null
}
}
</script>
服务端渲染 将vue-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
}
使用inject()方法 输出页面
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>
`)
})
})
源码地址:https://github.com/nuxt/vue-meta