The Be Sure Blog

Code Snippets | Problem Solving | Tips & Tricks

The Be Sure Blog banner

Getting started with global state management in Vue.js

posted on 1.2.2023 by Below Surface in "Vue.js"

This blog post is the documentation of me learning Vue.js for one week. We are now on day three and it is time for global state management with the built in Vuex. It took a lot of research from various sources that all could not 100% lead me to success to make it happen, so here we go:

When setting up a new Vue.js application, set a check mark to include the Vuex store. It is also possible to install it later, but this is how I did it.

In my test case I wanted to have a global state for the navigation status, to be shared between two components:

First of all, in store/index.ts, the default code looked like:

import { createStore } from 'vuex'

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

And without going any fancy about the toggleNav function, I changed it to be:

import { createStore } from 'vuex'

export default createStore({   state: {     showNav: false   },   getters: {   },   mutations: {     toggleNav(state) {       if ( state.showNav === false) return state.showNav = true;       return state.showNav = false;     }   },   actions: {   },   modules: {   } })

To be sure the store is imported into the application, check the main.ts file. It should include two things:

import store from './store'

And ".use(store)":


Now, within any view or component, I added this code to the script block:

<script lang="ts">
    import store from "../store";

    export default {         data() {             return {                 store,             }         },         methods: {             toggleNav() {       "toggleNav");             }         }     } </script>

And within the template block, now I can access the showNav boolean value like this:

{{  store.state.showNav }}

The HTML code for the button is the following:

    <div class="navigation-trigger" v-on:click="toggleNav">
        <div class="nav-icon" :class="{open:store.state.showNav}" >


state management

More posts of this category

Building a custom image slider in Vue.js

From a Vue.js newbie: How to build a custom image slider


Add smooth scrolling to a Vue 3 website

Adding smooth scrolling usually makes up for a much better UX, and it is easy to implement


Install and use the router in Vue 3

Learn how to implement page routing in Vue 3


How to send emails from a Vue 3 client app

Learn how to use Emailjs to send emails from your client app