Search code examples
vue.jsvuejs3vue-meta

How to create custom meta tags in Vue Meta 3?


For those coming here for first time: "I dropped vue-meta and went for @vueuse/head npmjs.com/package/@vueuse/head package instead. Works perfectly."

I am using Vue Meta 3 to provide meta data to the website. The API for this is here

I do not understand how to provide custom meta tags( e.g Open Graph tags such as og:type). This is what I have tried to do in a component:

setup() {
    useMeta({
      title: "Homepage",
      meta: [
          {name: "hunky:dory", content: "website"}
      ],
      description: "This is the homepage."
    })
  },

The HTML that gets outputted ends up like this:

<head>
 <title>Homepage</title>
 <meta name="description" content="This is the homepage.">
 <meta name="meta" content="website"> <!-- should be <meta name="hunky:dory content="website"> -->
</head>

If I change the code to this:

setup() {
    useMeta({
      title: "Homepage",
      "hunky:dory": [
          {content: "website"}
      ],
      description: "This is the homepage."
    })
  },

I get illegal HTML output:

<head>
     <title>Homepage</title>
     <meta name="description" content="This is the homepage.">
     <hunky:dory>website</hunky:dory> <!-- total nonsense -->
    </head>

How do I get the output to be:

<head>
         <title>Homepage</title>
         <meta name="description" content="This is the homepage.">
         <meta name="hunky:dory" content="website">
        </head>

Solution

  • There are 2 parts to getting og meta working -- I think I can help with part 1:

    1. Correct vue-meta syntax
    2. Server-Side Rendering (SSR)

    Part 1: vue-meta for Vue 3

    I wrote this with vue-class-component, and it seems to be working:

    meta = setup(() => useMeta(computed(() => ({
      title: this.event?.name ?? 'Event not found',
      og: {
        image: this.event?.bannerUrl ?? 'http://yourwebsite.com/images/default-banner.png'
      }
    }))))
    

    ...which presumably translates to this in vanilla Vue 3:

    setup() {  
      useMeta(
        computed(() => ({
          title: this.event?.name ?? 'Event not found',
          og: {
            image: this.event?.bannerUrl ?? 'http://yourwebsite.com/images/default-banner.png'
          }
        }))
      )
    }
    

    Result:

    <meta property="og:image" content="http://cloudstorage.com/images/event-123.png">
    

    References:

    Part 2: SSR

    Once I'd done part 1, I realized that I hadn't setup SSR... so I'm only rendering the meta for my users, not for Facebook's crawler (not very useful). I'm afraid I haven't fixed this yet on my project; perhaps someone else can pitch in that part!

    Until then, maybe this will get you started:

    Note: vue-meta is under the Nuxt GitHub organization => you might consider migrating to Nuxt v3 (which is built on top of Vue):