[Vuejs]-How to access vue store from a component when using with router

0👍

Didn’t quite understand what you mean, but it has nothing to do with the router. Please take a look at documentation of Vuex with options API, and Vuex with composition API.

Just created example how to use Vuex with composition api, because I personally prefer it. Here it is:

main.js

import { createStore } from "vuex";
import { createApp } from "vue";
import App from "./App.vue";

const store = createStore({
  state() {
    return {
      cart: []
    };
  },
  mutations: {
    addItem(state, item) {
      state.cart.push(item);
    }
  }
});

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

App.vue

<template>
  <TestVuex />
</template>

<script setup>
import TestVuex from "./components/TestVuex.vue";
</script>

TestVuex.vue

<template>
  <input type="text" v-model="input" />
  <div class="btn"><button @click="add">Add</button></div>
  <div>from the store:{{ cart }}</div>
</template>

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

const store = useStore();
const input = ref("");

const cart = computed(() => {
  return store.state.cart;
});

const add = () => {
  store.commit("addItem", input.value);
  input.value = "";
};
</script>

enter image description here

Leave a comment