Vue metaInfo undefined in watch

310 Views Asked by At

I am inserting vue-meta logic inside the current code and there seems to be a problem that metaInfo is not available yet when watch is triggered.

export default {
  metaInfo () {
    return {
      title: this.title,
      meta: [],
    }
  },
  watch: {
    article() {
      if (this.article) {
        this.generatedHtml = this.applySnippets();
      }
    },
  },
  computed: {
    article() {
      return this.$store.getters.CONTENT;
    },
    title() {
      if (this.article !== null) {
        return this.article.info.caption;
      }
      return '';
    },
  }
  created() {
    this.$store.commit('CLEAR_CONTENT');
    this.$store.dispatch('FETCH_CONTENT', { slug: this.slug, component: this });
  },
  methods: {
    applySnippets() {
      if (!this.article.snippets || this.article.snippets.length === 0) {
        return this.article.data.content;
      }
      this.article.snippets.forEach(snippet => {
        if (snippet.type === 'meta') 
          this.metaInfo.meta.push(snippet.object);
      });
    },

It fails that this.metaInfo is undefined during this Vue lifecycle phase. What to do?

1

There are 1 best solutions below

0
tony19 On BEST ANSWER

To access the metaInfo result in the Options API, use this.$metaInfo (note the $ prefix):

if (snippet.type === 'meta')
  this.$metaInfo.meta.push(snippet.object);
       

demo