How can I prevent the watch function from being triggered for a key other than the one selected in the data array?
import { useSessionStorage } from "@vueuse/core";
const defaultState = {
data: [
{ key: 1, name: "A" },
{ key: 2, name: "D" },
{ key: 3, name: "C" },
]
}
const state = useSessionStorage("settings", defaultState, {
mergeDefaults: true,
});
const key0Name = toRef(
() => state.value.data[0].name
);
watch(key0Name, (newOpts) => {
console.log("key0Name", newOpts);
});
state.value.data[0].name = "Z" // Triggers watch function.
state.value.data[1].name = "Z" // Also triggers watch function.
2
Answers
It looks like I have to use toRefs on the array of objects.
And if I want to watch the name:
It doesn’t when I try it out. Only changes to the value at index 0 trigger the watcher: