[Vuejs]-Vuex $state issue

1👍

Your examples look like it should work, but I would like to offer a different strategy that I think would be an improvement and should also solve your problem.

Create a getter in your store for the data you’re trying to access in your component.

So change your store to this:

 import Vue from 'vue'
 import Vuex from 'vuex'

  Vue.use(Vuex)

  export const store = new Vuex.Store({
    state: {
      users: [
       {id: 1, name: 'Adrian', email: 'adrian@email.pl'},
       {id: 2, name: 'Magda', email: 'magda@email.pl'}
      ]
    },
    getters:{
      users: state => return state.users
    }
  });

Then, in your component, use that getter to get your users.

<script>
 export default {
    name: 'usersNames',
    computed: {
     usersNames() {
       return this.$store.getters.users
    }
   }
 }
</script>

0👍

you could change main.js:import {store} from ‘./store’;

-1👍

Seems your vuex not inject into vue properly.

Maybe not related to your question, but just for best practice, better use mapState helper;
In your component:

import { mapState } from 'vuex'

export default {
  name: 'usersNames',
  computed: {
    ...mapState({
      usersNames: 'users'
    }),
    yourLocalComputed () {}
  }
}

Leave a comment