How to add arrays to Vue Meta
Updated by Tom Wells on
When building a website, blog or web-app, SEO is always a factor in acquiring an engaging audience for your content. If done right, a well-optimised website/blog/web-app will drive its own traffic from search engines. And best of all, it's free.
Vue and Nuxt have access to a superb package called vue-meta that applies metadata to your routes using Vue's built-in reactivity. The vue-meta
package allows you to change your page titles, descriptions and much more by adding a simple head()
method into your Vue components and pages.
Using arrays in vue-meta
There are some open graph schemas that accept an Array
(repetitions of the same metadata element) that further enrich your content for social media sites such as Facebook. For our example, we're going to use article:tag
as most blog posts contain one or more tags. In basic markup, several tags would appear like this in the <head>
:
<meta property="article:tag" content="vue" />
<meta property="article:tag" content="nuxt" />
<meta property="article:tag" content="javascript" />
So, how do we achieve this in vue-meta
? As always, it's quite simple! We simply map
through our array of tags to create the objects that vue-meta
accepts and use array destructuring to unpack the objects into our head
. Here's an example:
export default {
...,
head() {
const tags = this.post.tags.map((tag) => {
return {
hid: `article:tag:${tag}`,
property: 'article:tag',
content: tag
}
})
return {
meta: [
{},
...tags,
{}
]
}
},
...
}
In the example above, we're assuming this.posts.tags
is an array of tags. Change your code accordingly. Note that the hid
property needs to be uniquely named, hence including the tag in the ID.
Wrapping up
There are a surprising number of array tags in Open Graph where this example can be useful. Whether it's a video sharing web-app or a simple blog, chances are you'll need several of the same metadata elements at some point.
If you found this post useful or have any questions, follow me on Twitter and show your support.