Can't access state of store vuex

243 Views Asked by At

Here is of main file /main.js

import Vue from 'vue';
import App from './App.vue';
import vuetify from './plugins/vuetify';
import router from './router';
import store  from './store/index.js';

Vue.config.productionTip = false

new Vue({
  router,
  vuetify,
  store,
  render: h => h(App)
}).$mount('#app')

Here is store /store/index.js

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


Vue.use(Vuex);

const store= new Vuex.Store({
  state: {
    appNumber: 0
  }
})

export default store

Here is template /template

<template>
  <div>
    {{appNumber()}}
  </div>
</template>

<script>
export default {

  computed: {
    }
  ,
  methods: {
    appNumber() {
      return this.$store.state.appNumber;
  }
}};
</script>

The error is " Cannot read properties of undefined (reading 'state') "

I try to access file store index.js by import directly in template and it work. But I want to declare it on main.js file and can use by all file

2

There are 2 best solutions below

1
Goga On

Normally, we don't access the state directly outside of the store. Normally, we write getters and access them as follows: this.$store.getters["getAppNumber"]

In your store, define the getter as:

getters: {
   getAppNumber: state => state.appNumber,
}

Even better would be if you would ...mapGetters(["getAppNumber"]) to the computed property of the consuming component. Because then you can simply access the value with this.getAppNumber

1
blackcityhenry On

I could see your are trying to access the $store.state by using methods.

Beside using getter in Goga's answer, you are supposed to use computed if you want to get a reactive calculcated value within a instance.

And that you don't need the blanket anymore.

<template>
  <div>
    {{ appNumber }}
  </div>
</template>

<script>
export default {

  computed: {
     appNumber(){
         return this.$store.state.appNumber;
     }
  }
};
</script>