I created a vue app using vuejs 2 and vuex 3.
Here is the code: App.vue :
<template>
<div id="app">
<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>
<router-view></router-view>
<button v-on:click="increment">Test</button>
</div>
</template>
<script>
export default {
components: {
},
data() {
return {
}
},
methods: {
increment() {
this.$store.commit('increment')
console.log(this.$store.state.count)
}
},
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
store.js:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
})
main.js
import Vue from 'vue'
import router from './router.js'
import VueRouter from 'vue-router';
import App from './App.vue'
import Vuex from 'vuex'
import store from './store.js'
Vue.use(Vuex)
Vue.use(VueRouter)
Vue.config.productionTip = false
new Vue({
router: router,
store: store,
template: '<App/>',
components: { App },
render: h => h(App),
}).$mount('#app')
When I click at the button in App.vue file. it always throw error that this.$store is undefined. Did i do something wrong? But when i add the following code in the main.js file. Everything work smoothly.
Vue.prototype.$store = store;
But did I already registered the store in Vue constructor. Why do I need that code? Can anyone show me the best way to fix it`? Thank you.
Turns out I install wrong version of vuex (v4 instead of v3). Problem solved.