Throughout this series we've explored various store solutions both official and DIY. We'll end the series by taking a look at a home rolled solution w

Home Rolled Store with the Vue.js Composition API

submited by
Style Pass
2021-06-10 17:00:08

Throughout this series we've explored various store solutions both official and DIY. We'll end the series by taking a look at a home rolled solution with Vue 3's composition API.

Before we continue, if you haven't read the previous articles in this series, I encourage you to go back and at least look over articles 1. What is a Store and 2. Vuex, the Official Vue.js Store as we won't go much into principles in this article, but rather focus on implementation.

As opposed to Vuex or Pinia the composition API comes shipped with Vue 3, therefore there is no external package to install and setup. If you are using Vue 2, you can install the composition-api Vue plugin.

Defining a store with the composition API can be approached in a number of different ways. Since it's a home rolled solution it's really up to you to decide exactly how you want to structure it, but the important piece is that your state is passed to the reactive method so that your state is reactive. In fact, reactive is the equivalent Vue.observable renamed in Vue 3 to avoid confusion with RxJS observables.

As an alternative to reactive you could use ref but I prefer reactive for this use case. ref is typically used for primitive values such as strings or booleans while reactive is used for objects. Since, we've been pretty well conditioned to think about state as a single entity, it works well to reference all the state inside of the store under a state object and thus I prefer reactive. Using reactive also means I don't have to use .value when referring to any of the state, which feels more intuitive to me.

Leave a Comment