Using vue-meta with computed properties

2.1k Views Asked by At

I'm trying to add dynamic meta tags to my article page. Articles are stored in a VueX store and I use a computed property to get the article I want to display :

computed: {
  article() {
   return this.$store.state.articles.filter(article => article.id == this.$route.params.id);
  }
}

I am using vue-meta for this (is there a better way to do it? I'm not using Nuxt so I don't have server side rendering).

The correct way to use it would be :

metaInfo() {
  return {
    title: this.article.title,

    meta: [
     {property: 'og:title', content: this.article.title},
     {property: 'og:site_name', content: 'Website Name'},
     {property: 'og:type', content: 'website'},
     {property: 'og:url', content: 'url.com'},
     {property: 'og:image', content: this.article.image},
     {property: 'og:description', content: this.article.description},
     ]
   }
 }

But it only works if the article is stored in data(). Since the component return dynamic articles, how can I access the filtered article in the computed property?

Thank you for you help

1

There are 1 best solutions below

2
On

You need to name your computed property as article, also thanks to @ssc-hrep2 use find instead of filter to return the matched object in an array, since filter returns an array:

computed: {
  article () {
    return this.$store.state.articles.find(article => article.id == this.$route.params.id)
  }
}

Or use mapState from vuex:

import { mapState } from 'vuex'

computed: mapState({
  article: state => state.articles.find(article => article.id == this.$route.params.id)
})