在使用Vue Router加载npm包名时,避免使用简短的标签标题



对于Vue 3和vue-router,我在获得准确的选项卡标题时遇到了麻烦-在第一次加载时,NPM包的名称client显示了几百毫秒。

目前,标签标题是在router.js路由的meta选项中分配的,它被导入到Vue应用的main.js入口点。

const router = createRouter({
history: createWebHistory(),
routes: [
{
path: "/",
component: Landing,
name: "home",
meta: {
title: "My Cool Title",
},
},

App.vue中设置了一个监视器,用于将文档标题设置为:

watch: {
"$route" (to) {
document.title = to.meta.title || "Fallback";
}
}

然而,在最初加载应用程序时,名称"client"被用作标题几乎一秒钟,因为它是package.json中的项目名称。此外,在路由之间切换(这不会触发重新加载)也会保持前一个标题半秒左右。

在加载之前,我如何才能将文档标题设置为所需的元标记?

由于您使用的是vue 3,我建议使用这个名为veuse/head:

的插件。安装:

pm i @vueuse/head -S

用法:

main.js

import { createApp } from 'vue'
import { createHead } from '@vueuse/head'
const app = createApp()
const head = createHead()
app.use(head)
app.mount('#app')

App.vue:

<script>
import { defineComponent, computed } from 'vue'
import { useHead } from '@vueuse/head'
import {useRoute} from 'vue-router'
export default defineComponent({
setup() {
const route=useRoute()
useHead({
title: computed(() => route.meta.title),

})
},
})
</script>

您可以尝试如下:

  • 为您的监视器设置immediate: true
watch: {
"$route": {
handler(to) {
document.title = to.meta.title || "Fallback";
},
immediate: true
}
}
}
  • 在main.js中废料看守方法和设置全局前守卫
router.beforeEach((to, from, next) => {
document.title = to.meta.title
next()
})

最新更新