Search code examples
vue.jsnuxt.jsvuexmixins

Nuxt - How to call a getters in a global mixins?


Hi everyone here is the mixin code I wrote as I want to use this for default.vue and error.vue layout. I am trying to avoid duplicating code in two layout.

export default {
  provide () {
    return {
      copyRight: this.getCopyrightText,
      email: this.getEmail,
      socials: this.getSocials
    }
  },
  computed: {
    getMenu () {
      return this.store.getters['general/getMenu'].menu
    },

    getSocials () {
      return this.store.getters['general/getSocialDetails']
    },

    getCopyrightText () {
      return this.store.getters['general/getCopyRight']
    },

    getEmail () {
      return this.store.getters['general/getEmail']
    }
  },
  middleware: 'load-menu-items'
}

This is what I get: Cannot read property 'length' of undefined

What am I doing wrong?


Solution

  • In your component I assume you're using .length on the data you're receiving from the getter method, which is probably where the error occurs.

    First of all you should debug to see if your getter is actually working as expected. Try this and look at output in console for every getter computed property. If undefined is printed to the console you'll get the error you posted if you're using .length on it

    getEmail () {
      let data = this.store.getters['general/getEmail'];
      console.log(data);
      return data;
    }
    

    If you post the component which is using this mixin maybe I can help you further.