Search code examples
vue.jsnuxt.jsvuex

[Vue warn]: Property or method "stateSidebar" is not defined on the instance but referenced during render


I know this seems like a question that would be easy to find, but my code worked some time ago. I am using a Vuex binding to check if my sidebar should be visible or not, so stateSidebar should be set within my entire project.

default.vue

<template>
  <div>
    <TopNav />
    <SidebarAuth v-if="stateSidebar" />
    <Nuxt />
  </div>
</template>

<script>
import TopNav from './partials/TopNav';
import SidebarAuth from './partials/SidebarAuth';

export default {
  components: {
    TopNav,
    SidebarAuth
  },
  methods: {
    setStateSidebar(event, state) {
      this.$store.dispatch('sidebar/setState', state)
    }
  }
}
</script>

store/sidebar.js

export const state = () => ({
  stateSidebar: false
});

export const getters = {
  stateSidebar(state) {
    return state.stateSidebar;
  }
};

export const mutations = {
  SET_SIDEBAR_STATE(state, stateSidebar) {
    state.stateSidebar = stateSidebar;
  }
};

export const actions = {
  setState({ commit }, stateSidebar) {
    commit('SET_SIDEBAR_STATE', stateSidebar);
  },
  clearState({ commit }) {
    commit('SET_SIDEBAR_STATE', false);
  }
};

plugins/mixins/sidebar.js

import Vue from 'vue';

import { mapGetters } from 'vuex';

const Sidebar = {
  install(Vue, options) {
    Vue.mixin({
      computed: {
        ...mapGetters({
          stateSidebar: 'sidebar/stateSidebar'
        })
      }
    })
  }
}

Vue.use(Sidebar);

nuxt.config.js

 plugins: ["./plugins/mixins/validation", "./plugins/axios", "./plugins/mixins/sidebar"],

Solution

  • If you're creating a mixin, it should be in /mixins
    So for example /mixins/my-mixin.js.

    export default {
      // vuex mixin
    }
    

    Then import it like this in default.vue

    <script>
    import myMixin from '~/mixins/my-mixin`
    
    export default {
      mixins: [myMixin],
    }
    

    This is not what plugins should be used for tho. And IMO, you should definitively make something simpler and shorter here, with less boilerplate and that will not be deprecated in vue3 (mixins).

    This is IMO the recommended way of using it

    <template>
      <div>
        <TopNav />
        <SidebarAuth v-if="stateSidebar" />
        <Nuxt />
      </div>
    </template>
    
    <script>
    import { mapState } from 'vuex'
    
    export default {
      computed: {
        ...mapState('sidebar', ['stateSidebar']) // no need to use object syntax nor a getter since you're just fetching the state here
      },
    }
    </script>
    

    No mixin, no plugin entry.