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
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:
Even better would be if you would
...mapGetters(["getAppNumber"])to thecomputedproperty of the consuming component. Because then you can simply access the value withthis.getAppNumber