Watchers inside setup functions don't get invoked #1792
-
Reproductionhttps://stackblitz.com/edit/github-3uy8yt?file=src/App.vue Steps to reproduce the bugLooking at various discussions, it seems like I should be able to define a watcher inside a store setup function. However in practice it doesnt seem to work. In the linked stackblitz I have modified the official example to use setup functions, and have two watchers defined: First is inside cart.js: export const useCartStore = defineStore('cart', () => {
const rawItems = ref([]);
....
watch(rawItems, (oldItems, newItems) => {
console.log('Watcher invoked', oldItems, newItems);
});
....
}) Second is inside App.vue: const cart = useCartStore();
watch(cart.rawItems, (prevItems, newItems) => {
console.log('component level watcher: ', prevItems, newItems);
}); Expected behaviorBoth watchers get invoked whenever an item gets added/removeed to the cart Actual behaviorThe second gets invoked everytime an item is added or removed. But the first never gets invoked. Additional informationNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
You need a deep watcher for arrays (https://vuejs.org/guide/essentials/watchers.html). You will notice the same happens in plain vue BTW the second watcher should be: watch(() => cart.rawItems, ..., { deep: true }) There is a small section explaining this in the same doc page |
Beta Was this translation helpful? Give feedback.
-
Thank you. Why is the arrow function needed in the second example though ? |
Beta Was this translation helpful? Give feedback.
You need a deep watcher for arrays (https://vuejs.org/guide/essentials/watchers.html). You will notice the same happens in plain vue
BTW the second watcher should be:
There is a small section explaining this in the same doc page