How to use global state or variable in Vue.js (Simplest Vue.js Tutorial)
We love Reactjs, but it is indeed too complex when you need to call a global variable.
So can Vue.js make it more simple than redux? Let’s have a look together!
Before we start
First I want you to have a basic understanding of Vue, you need to know how to use
Vue CLI
to create an empty project.
Then you have to understand the basic structure of a Vue project, I mean template, script, CSS.
Finally, I need you to take a look at https://medium.com/js-dojo/vuex-2638ba4b1d76
Basic Concepts
State
It’s nothing but as same as the Reactjs state. It’s a global variable, where saves the data that affect the view of your website.
Mutations
In this section, you define those scripts that change the
state
.Actions
You should put every asynchronous operation in it, for example:
fetch API
.Add Together
main.js
import Vue from 'vue' import Vuex from 'vuex' import App from './App.vue'Vue.config.productionTip = false Vue.use(Vuex)const API_BASE = "http://127.0.0.1:5000/" + 'api/' const API_FUNCTION_GET_FILES = API_BASE + 'files/' const API_FUNCTION_UPDATE_FILES = API_BASE + 'update/'const store = new Vuex.Store({ state: { files: undefined, }, mutations: { setFiles(state, files) { state.files = files }, }, actions: { async getFiles() { return fetch(API_FUNCTION_GET_FILES) .then((result) => result.json()) .then((files) => { this.commit('setFiles', files) }); }, async updateFiles() { await fetch(API_FUNCTION_UPDATE_FILES) return store.dispatch('getFiles') } }, })new Vue({ store, render: h => h(App), created: () => { store.dispatch('getFiles') } }).$mount('#app')
App.vue
<template> <div id="app"> <MyList/> </div> </template><script> import MyList from "./components/MyList.vue";export default { name: "app", components: { MyList }, }; </script>
./components/MyList.vue
<template> <div class="hello"> <button v-on:click="update">update files</button> <br /> {{this.$store.state.files}} </div> </template><script> export default { name: "MyList", methods: { update() { this.$store.dispatch("updateFiles"); } } }; </script>