Search code examples
vue.jsvue-componentvuexvuejs3vuex4

Vue 3 + vuex store is not defined


I used Vue 3 cli to install new testing ground for store and router to learn those.

Project come like this :

main.js:

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";

createApp(App).use(store).use(router).mount("#app");

store.js (just added count for testing):

import { createStore } from 'vuex'

export default createStore({
  state: {
    count: 0
  },
  mutations: {},
  actions: {},
  modules: {},
});

and in views: Home.vue:

<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png" />
    <HelloWorld msg="Welcome to Your Vue.js App" />
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from "@/components/HelloWorld.vue";

export default {
  name: "Home",
  components: {
    HelloWorld,
  },
  mounted() {
    console.log(store.state.count)
  },
};
</script>

By all that I have read I should be able to access store in component with:

mounted() {
        console.log(store.state.count)
      },

But i get store is not defined. While it is obliviously imported and used in main app with index.js's:

import store from "./store";
    
    createApp(App).use(store)

I heave spent hours on this, please advise. This is out of the box cli installation, i don't understand what they wont me to do...


Solution

  • You've to access it using this and prepended by $ sign:

    export default {
      name: "Home",
      components: {
        HelloWorld,
      },
      mounted() {
        console.log(this.$store.state.count)
      },
    };