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:
- the navigation button, which has an opening/closing animation
- the navigation itself, which is hidden by default and shown on click of the navigation button
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)":
createApp(App).use(store).mount('#app')
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() { this.store.commit("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:
<template> <div class="navigation-trigger" v-on:click="toggleNav"> <div class="nav-icon" :class="{open:store.state.showNav}" > <span></span> <span></span> <span></span> </div> </div> </template>