Align Alpine Store to Vuex
If you are used to Vue and Vuex, but use Alpine.js for quick prototyping, you might want your code to be as close to your prefered environment as possible.
With just some tweaks, you can make Alpine's store behave like Vuex:
function createStore({ state, actions, getters }) {
Alpine.store("state", state);
if (actions) {
Alpine.store("actions", actions);
}
if (getters) {
const generatedGetters = {};
Object.entries(getters).forEach(([name, fn]) => {
Object.defineProperty(generatedGetters, name, {
get() {
return fn(Alpine.store("state"));
},
});
});
Alpine.store("getters", generatedGetters);
}
Alpine.store("dispatch", function (action, payload) {
return Alpine.store("actions")[action](
{ state: Alpine.store("state"), getters: Alpine.store("getters") },
payload
);
});
}
You are then able to create and use the store in the usual way:
const state = {
pages: [],
};
const actions = {
createPage({ state }, payload) {
state.pages.push(payload);
},
};
const getters = {
pageById: (state) => (id) => {
return state.pages.find((page) => page.id === id);
},
};
createStore({ state, actions, getters });
In this example/proof-of-concept implementation, proper handling (modification) of the state (which should be immutable) is left out.
Hint: There's Petite Vue for rapid development (that is, without the need of a compile/transpile step).
Comments
There are no comments yet.
Thanks for your contribution!
Your comment will be visible once it has been approved.
An error occured—please try again.
Add Comment