vue js store
Here is an example of how Vuex can be used to manage the state of a simple Vue.js application:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0,
message: "Hello World"
},
mutations: {
increment (state) {
state.count++
},
updateMessage(state, payload) {
state.message = payload
}
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
},
getters: {
countDouble: state => state.count * 2,
messageLength: state => state.message.length
}
})
export default store
In this example, we have defined the following in the store:
state
: An object that holds the data that we want to share across different components of the app. In this case, it holds acount
variable and amessage
variable.mutations
: An object that holds functions that change the state. In this case, we have two mutationsincrement
andupdateMessage
actions
: An object that holds functions that perform asynchronous operations and commit mutations. In this case, we have one actionincrementAsync
getters
: An object that holds functions that retrieve computed properties from the state. In this case, we have two getterscountDouble
andmessageLength
In themain.js
file or in the new Vue()
instance we need to import the store and make it available for the entire application.
import store from './store'
new Vue({
store,
render: h => h(App),
}).$mount('#app')
Then in any component, we can access the store and use it like this
<template>
<div>
<h1>{{ $store.state.count }}</h1>
<h1>{{ $store.state.message }}</h1>
<button @click="incrementCount">Increment</button>
<button @click="updateMessage">Update Message</button>
<button @click="incrementCountAsync">Increment Async</button>
<h2>{{ countDouble }}</h2>
<h2>{{ messageLength }}</h2>
</div>
</template>
<script>
export default {
computed: {
countDouble() {
return this.$store.getters.countDouble
},
messageLength() {
return this.$store.getters.messageLength
}
},
methods: {
incrementCount() {
this.$store.commit('increment')
},
updateMessage() {
this.$store.commit('updateMessage', "New Message")
},
incrementCountAsync() {
this.$store.dispatch('incrementAsync')
}
}
}
</script>
I hope you found it useful!