Creating a Store without Vuex in Vue.js 2.6
Vue.js 2.6 introduced some new features, and one I really like is the new global observable API.
Now you can create reactive objects outside the Vue.js components scope. And, when you use them in the components, it will trigger render updates appropriately.
In that way, you can create very simple stores without the need of Vuex, perfect for simple scenarios like those cases where you need to share some external state across components.
For this tip example, you're going to build a simple count functionality where you externalise the state to our own store.
First create store.js
:
import Vue from "vue";
export const store = Vue.observable({
count: 0
});
If you feel comfortable with the idea of mutations and actions, you can use that pattern just by creating plain functions to update the data:
import Vue from "vue";
export const store = Vue.observable({
count: 0
});
export const mutations = {
setCount(count) {
store.count = count;
}
};
Now you just need to use it in a component. To access the state, just like in Vuex, we'll use computed properties, and methods for the mutations:
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="setCount(count + 1);">+ 1</button>
<button @click="setCount(count - 1);">- 1</button>
</div>
</template>
<script>
import { store, mutations } from "./store";
export default {
computed: {
count() {
return store.count;
}
},
methods: {
setCount: mutations.setCount
}
};
</script>
If you want to try this example yourself, I've compiled for you in this CodeSandbox, go check it out!
Remember you can read this tip online (with copy/pasteable code), and don't forget to share VueDose with your colleagues, so they also know about these tips as well!
Related Articles
The new Provide and Inject in Vue 3
Getting stuck into the prop drilling? Learn how provide/inject can make your components more flexible and independent in this short tutorial.
Jul 18, 2022
Sep 24, 2019
Using Scoped Slots in Vue.js
Quick example on how to use scoped slots for component reusability in vuejs
Sep 15, 2019
Sponsors
VueDose is proudly supported by its sponsors. If you enjoy it, consider supporting it to ensure the project maintainability.