Prevent brief tab title of npm package name when loading with Vue Router

With Vue 3 and vue-router, I'm having trouble having accurate tab titles - upon first load, the name of the NPM package, client, is displayed for several hundred milliseconds.

Currently, tab titles are assigned in the meta option of routes in router.js, which is imported to the main.js entrypoint of the Vue app.

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

A watcher is set up in App.vue for setting the document title as so:

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

However, upon initially loading the app, the name "client" is used as a title for almost a second, as it is the name of the project in package.json. Also, switching between routes (which doesn't trigger a reload) also holds the previous title for half a second or so.

How can I get the document title to be set to the desired meta tag before it is even loaded?


#1 Answers

Since you're working with vue 3 I recommend to use this plugin called vueuse/head :

Installation :

pm i @vueuse/head -S

Usage :

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>

Comments