While vuex
is the best and official lib around to manage state in a Vue.js application, vue-stash
is actually a nice and simpler alternative.
Two cases where you don’t want to use vuex
to share data across components :
-
You are a beginner and the redux-style state management concepts used in
vuex
are difficult to grasp. -
You application is pretty simple, you don’t need time-travel and vue-devtools, you just want to use Vue.js’s reactive data binding system.
Let me introduce you to vue-stash
.
Initialization
You import the plugin, and initialize your store in your root component.
import VueStash from 'vue-stash'
Vue.use(VueStash)
new Vue({
el: '#app',
data: {
store: {
user: { ... }
}
}
})
data.store
contains the data you want to share across your different components.
Nothing fancy here, just another Vue.js plugin.
Access from children components
Two ways to access vue-stash
data store.
-
store
property in the component declaration binds part of the store to the component.
Vue.component('child-component', {
store: {
user
},
render (h) {
return (
<div>
Hi {{ user.name }}
</div>
)
}
})
-
this.$store
is a reference to the global and reactive store object.
Vue.component('child-component', {
render (h) {
return (
<div>
Hi {{ $store.user.name }}
</div>
)
}
})
Vue Stash vs Vuex
This paragraph is intended for devs who are familiar with Vuex.
State
Original state is declared in the root component. We can easily put it in a separate file and import that file to the root component.
// state.js
export default {
user: {
firstName: 'Chuck',
lastName: 'Norris'
}
}
// index.js
import state from './state.js'
new Vue({
el: '#app',
data: {
store: state
}
})
Actions/Mutations
You already understood that there are no actions nor mutations in vue-stash
. Vue’s reactive data binding system is used and does the job.
Pros : less code to write, no separate files
Cons : no time travel/devtools, and… no separate files ;)
Getters
If you need a getter to access a sub-object of your store, it is possible out-of-the-box :
Vue.component('child-component', {
store: {
firstName: 'user.firstName'
}
})
If you need the getter to provide some sort of logic to your data, you will need to use a computed property :
// ChildComponent.js
Vue.component('child-component', {
store: {
user
},
computed: {
fullName () {
return this.user.firstName + ' ' + this.user.lastName
}
}
})
Conclusion
While vue-stash
is a beginner-friendly approach to state management, it is always best to know the recommended way to do such, aka Vuex.
For devs that are already familiar with Redux concepts and are looking for a simple alternative, this is definetely a good pick.