安装 vue-meta

npm i -S vue-meta@next
目前 vue-meta3 还是处于 alpha 阶段,不要低于 3.0.0-alpha.7

项目结构

.src
├── App.vue
├── global
│   └── vue-meta
│       ├── component.tsx
│       └── index.ts
├── main.ts
├── router
│   └── index.ts
└── views
    ├── About.vue
    └── Home.vue

开发

创建一个vue-meta的管理器,并 use 到 app 中

// global/vue-meta/index.ts
import { createMetaManager } from 'vue-meta'
export default createMetaManager(false, {})
// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import router from '@/router'
import vueMetaManager from '@/global/vue-meta'

const app = createApp(App)

app
 .use(router)
 .use(vueMetaManager)

app.mount('#app')

创建一个组件,专门处理 meta

// global/vue-meta/components.tsx
import router from '@/router'
import { watch } from '@vue/runtime-core'
import { Options, setup, Vue } from 'vue-class-component'
import { SlotScopeProperties, useMeta } from 'vue-meta'

@Options<VueMeta>({
  render () {
    const slots = {
      title: ({ content }: SlotScopeProperties) => {
        return content ? `${content} | SITE_NAME` : 'SITE_NAME'
      },
    }

    // metainfo是全局组件,由vue-meta注入
    // 这里不可以使用 h('metainfo'),无法正确渲染 metainfo 组件。原因未知
    return <metainfo v-slots={slots} />
  },
})
export default class VueMeta extends Vue {
  protected meta = setup(() => {
    const { meta } = useMeta({
      title: '',
    })

    // 监听当前路由对象 修改 meta 信息
    watch(router.currentRoute, () => {
      const route = router.currentRoute.value

      const metaInfo = route.meta?.metaInfo ?? true

      // true:使用 route.meta.title
      // false:由页面组件通过 useMeta 修改
      // object:更新
      if (metaInfo === true) {
        meta.title = route.meta?.title || ''
      } else if (metaInfo && metaInfo !== false) {
        Object.assign(meta, metaInfo)
      }
    })

    return meta
  })
}

将组件放到 App.vue 中

<!-- App.vue -->

<template>
  <VueMeta />

  <div id="nav">
    <router-link to="/">
      Home
    </router-link> |
    <router-link to="/about">
      About
    </router-link>
  </div>
  <router-view />
</template>
<script lang="ts">
import { Options, Vue } from 'vue-class-component'
import VueMeta from '@/global/vue-meta/component'

@Options({
  components: {
    VueMeta,
  },
})
export default class Home extends Vue {
}
</script>

对于某些特殊的页面,可以在页面组件里修改meta

<!-- views/Info.vue -->
<script lang="ts">

import { Options, Vue, setup } from 'vue-class-component'
import { useMeta } from 'vue-meta'
export default class Info extends Vue {
    meta = setup(() => {
        const { meta } = useMeta({
          title: 'info',
        })
        return meta
    })
    
    mounted() {
        // 可以随时修改
        this.meta.title = '有新的消息'
    }
}
</script>

ci0n
195 声望7 粉丝

一个前端