Vuez — A very simple but powerful option for state management in Vue.js projects
Hi,
Here in medium, I want to introduce a new state management library for Vue.js projects named Vuez. You can check the github repo at: https://github.com/markselby9/vuez.
In short, Vuez is a centralized monitoring ‘store’ which is accessible for all your Vue components after installing Vuez. From each component, you can access the store through this.$store
.
The store concept in Vuez is very simple, imagine an excel table with three columns: ‘name’, ‘object’, ‘actions’. Whenever you are interested in monitoring an object or an event, you would like to start a new column in the table with a new name, with an object you plan to monitor. Then put everything you want to do when the object changed, as functions in the ‘actions’ column. Whenever you want to care about the ‘name’, you use store.observe(this_name)
to observe it, if the object
column's value has changed, all actions
related to the name
would be triggered.
It has only two set of APIs:
- Observe/unobserve
store.observe(name, observing_object)
, takes two parameters: name is a string for the observer, and observing_object is an object to observe. If a name is firstly created as an observer’s name (firstly used in observe function), the object would be recorded. Then everytime whenever the observe function is called with the name, all actions with the name would be triggered if and only if the observing_object
is changed.
store.unobserve(name)
would cancel every action and observers related to the name.
2. Action
store.action(name, action_function)
, takes two parameters: name is a string for the observer, and action_function is the function to act when the object is changed during an 'observe'. The action_function
here can have a parameter representing the current object value of the observing object.
With these simple APIs, Vuez can deal with many troublesome event handling such as data communication, monitoring data change, etc.
Let’s check a very simple example.
// Make sure to call Vue.use(Vuez) first before usageconst store = new Vuez.Store();
let changingObject = {
number: 1
};
store.observe('changing', changingObject);
store.action('changing', (obj) => {
console.log(obj.number);
});
observeObject.number = 2;
store.observe('changing', changingObject); // trigger the action and console would show '2'
For somehow more detailed examples to use Vuez in your Vue.js projects, please check these links:
- Todo List
- Weather Application A weather application using Vuez and Vue2.x.
Currently Vuez is compatible with both Vue1.x and 2.x. As a newborn project, Vuez is currently under rapid development, and has a lot of space to improve. So please kindly give some suggestions, issues when you faced in usage, and PR if you’re interested. The more the better! :)
Thanks again for your time.