VueJS Working with Vuex for State Management

Hello dev's, today I'll show you how to use Vuex in you vue 3 project. Vuex is one of the most popular library for state management. One of the main feature of State management is, it is independent from one component to another component. That's mean we can use any state to any component. So, let's see how we can easily use vuex in our vue 3 project.

Table of Contents

  1. Setup index.html
  2. Output

Setup index.html

Here we we'll setup our project to use vue 3 and vuex 4. And also we'll see the CDN version of vue and vuex and of course you can use on your project which can be based on component/template wise also. So, let's see the below code snippet first then we'll discuss the scenario.

index.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>Creating a Custom Directives with VueJ - shouts.dev</title>
</head>
<body>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/4.1.0/vuex.global.js"></script>

<div id="app">

<p>Count: {{ count }}</p>
    <button @click="increment">Increment</button>
</div>




<script>
  const store = Vuex.createStore({
    state: {
      count: 0
    },
    mutations: {
      increment(state) {
        state.count++
      }
    }
  })

    const app = Vue.createApp({
      computed: {
      count() {
        return this.$store.state.count
      }
    },
      methods: {
      increment() {
        this.$store.commit('increment')
      }
    }
    })

   app.use(store);
    app.mount('#app');
  </script>
</body>
</html>

In this example, we use the Vuex.createStore method to create our store, and then register it with our Vue.js app using app.use(store). We also use this.$store to access the store in our component, and this.$store.commit to commit mutations to the store.

By including the Vuex script tag in your HTML file, you can use Vuex in your Vue.js application without needing to install it using a package manager like NPM or Yarn.

That's it for today. I hope you've enjoyed this tutorial. Thanks for reading. ๐Ÿ™‚