SSR学习笔记(六) meta信息处理

278 阅读1分钟

需要处理的meta标签 index.html

<title></title>
<meta name="keywords" content="">
<meta name="description" content="">

安装vuex-router-sync用于在store中读取路由配置

npm i vuex-router-sync -S

main.js使用vuex-router-sync

xxxxx
import { sync } from 'vuex-router-sync'

xxxxx

export const createApp = () => {
  xxxxx
  sync(store, router)
  xxxxx
}

路由中配置meta信息 src/router/index.js

const routes = [
  {
    path: '/',
    name: 'home',
    component: Home,
    meta: {
      title: 'articleList',
      keywords: 'rty ssr home vuex vue3 vue-router axios',
      description: 'this is a ssr app by rty, it can run in any website, welcome to use this website',
      keepAlive: false
    }
  },
  {
    path: '/article',
    name: 'article',
    component: Article,
    meta: {
      title: 'articleDetail',
      keywords: 'axios vue-router vue3 vuex home ssr rty bruno',
      description: 'welcome to use this website, this is a ssr app by rty, it can run in any website',
      keepAlive: false
    }
  }
]

服务端替换meta信息 server.js

if (isProd) {
    xxxxx

    const manifest = require('./dist/client/ssr-manifest.json')
    const { appHtml, state, preloadLinks } = await render(url, manifest)
    const { title, keywords, description } = state.route.meta
    html = template
      .replace('<!--preload-link-->', preloadLinks)
      .replace(`<!--ssr-outlet-->`, appHtml)
      .replace('\'<!--vuex-state-->\'', JSON.stringify(state))
      .replace('<title>', `<title>${title}`)
      .replace('<meta name="keywords" content="">', `<meta name="keywords" content="${keywords}">`)
      .replace('<meta name="description" content="">', `<meta name="description" content="${description}">`)
}

客户端替换meta信息 src/entry-client.js

if (window.__INITIAL__STATE__) {
  store.replaceState(window.__INITIAL__STATE__)
}

router.beforeEach((to, from, next) => {
  const { title, keywords, description } = to.meta
  document.title = title
  const keywordsMeta = document.querySelector('meta[name="keywords"]')
  keywordsMeta?.setAttribute('content', keywords)
  const descriptionMeta = document.querySelector('meta[name="description"]')
  descriptionMeta?.setAttribute('content', description)
  next()
})

xxxxx