乐趣区

关于vue.js:vue3使用vuemeta

装置 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
├── store
│   └── index.ts
├── types
│   └── vue-router.d.ts
└── views
    ├── About.vue
    └── Home.vue

开发

// 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')
// 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 -->

<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>

尚未实现,先放出代码,后续补上解释

退出移动版