Blog>
Snippets

Using Provide/Inject with a Vuex Store

Demonstrate how to use provide/inject to make a Vuex store accessible in the component tree without using mapState or mapGetters.
import { createStore } from 'vuex';

// Create a new Vuex store
const store = createStore({
  state() {
    return {
      count: 0
    };
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  }
});

export default store;
This code creates a new Vuex store with a simple state containing a count property and a mutation to increment it. This store will be provided to the component tree.
import { createApp } from 'vue';
import App from './App.vue';
import store from './store'; // Import the store created above

const app = createApp(App);

// Provide the store instance to the entire app
app.provide('store', store);

app.mount('#app');
In the main entry file, the Vuex store is provided to the Vue application using the `provide` function. All components within the app can now inject the Vuex store.
<script>
export default {
  inject: ['store'], // Inject the Vuex store provided in the root instance
  computed: {
    count() {
      return this.store.state.count; // Access the Vuex store's state directly
    }
  },
  methods: {
    incrementCount() {
      this.store.commit('increment'); // Commit a mutation to the Vuex store
    }
  }
};
</script>
This component script injects the Vuex store and uses it to create a computed property for the count state and a method to dispatch a mutation. The Vuex store is accessed directly through this.store without using mapState or mapGetters.