[Vuejs]-How does Vuex 4 createStore() work internally

4👍

createStore() method can be used on your setup method.

On your main.js, you could do something like this

import { createApp } from 'vue'
import store from './store'

createApp(App).use(store).use(router).mount('#app')

store.js

import { createStore } from 'vuex';

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

To access your store, you don’t need to import store.js anymore, you could just use the new useStore() method to create the object. You can directly access your store using it just as usual.
your-component.js

<script>
import { computed } from "vue";
import { useStore } from "vuex";

export default {
  setup() {
    const store = useStore();

    const isAuthenticated = computed(() => store.state.isAuthenticated);
    const logout = () => store.dispatch("logout");
    return { isAuthenticated, logout };
  },
};
</script>

To use your store in the route.js file, you could simply imported the old fashion way.
route.js

import Home from '../views/Home.vue'
import store from '../store/'

const logout = () => {
  store.dispatch("auth/logout");
}

export const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  }
]

Leave a comment