Uses raw @vue/reactivity functions
Supports Vuex-devtools
Minimal overhead
Allow directly state manipulation (without using mutation)
function cart() {
const list = ref<{id: string, name: string, price: number}[]>([]);
function addProduct(product) {
list.value.push(product);
}
function removeProduct(product) {
const index = list.value.findIndex(item => item.id === product.id);
list.value.splice(index, 1);
}
function clear() {
list.value = [];
}
const totalPrice = computed(() => {
return list.value.reduce((total, item) => item.price, 0);
});
return { list, addProduct, removeProduct, clear, totalPrice };
}
function cartActions(cart: ReturnType<typeof cart>) {
const cancel = watch(cart.list, () => console.log('list change'), {deep: true});
onDestroyWidok(() => console.log('say bye!'));
onDestroyWidok(cancel);
return {
async order() {
await post('order', cart.list);
cart.clear();
}
};
}
const useCart = defineWidok('cart', cart, cartActions);
//destroyWidok(useCart()) to run teardown logic and delete instance
defineWidok(
name: string,
stateFactory: () => T,
managementFactory: (state: T) => R
): () => T & R
exported ref will be watched for changes
[${store name}] ${ref fieldKey}
mutations are created from function exported by stateFactory. Commit type is a function.name or fieldKey of export
[${store name}] ${type}
actions are created from function exported by managementFactory. Dispatch type is a function.name or fieldKey of export
[${store name}] ${type}
Author: wszerad
Source Code: https://github.com/wszerad/widok
#vue #vuejs #javascript #vue3