6
May
If you have multiple components and you would like to share some data among those components, then vuex is a good choice for that. It’s a state management tool that can be used with Vue.
We are not going to discuss advanced Vuex usage here, instead we will cover very basic Vuex tips, so that you can get started with Vuex.
Assume that we have two components say ButtonComp and DisplayComp.
First component displays a button to click and the second component displays the number of first component’s button clicks. So we need to create a store.js with count as a state. Initial value of it will be zero. That means count stores the number of button clicks and initially number of button clicks will be zero. If user click on the button, we should increment count by one.
Now first of all we need a file named store.js with content as shown below
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
setCount (state, count) {
state.count = count;
},
},
getters: {
getCount: state => {
return state.count
}
},
actions: {
setCount: (context, count) => {
context.commit('setCount', count)
},
}
})
Now let’s define two components, ButtonComp.vue and DisplayComp.vue
ButtonComp.vue content is
<template>
<div>
Set Count
<button type="button" class="btn btn-primary"
@click="setCount()">Set Count</button>
</div>
</template>
<script>
import { store } from '../store';
export default {
data() {
return {
}
},
methods: {
setCount() {
store.dispatch('setCount', 1);
},
},
}
</script>
And DisplayComp.vue content is
<template>
<div>
<h2>Button clicks</h2>
{{ count }}
</div>
</template>
<script>
import { store } from '../store';
export default {
data() {
return {
}
},
methods: {
},
computed: {
count () {
return this.$store.getters.getCount + " is the click count";
},
}
}
</script>