Home > database >  watch is not triggered when empty the ref object
watch is not triggered when empty the ref object

Time:03-22

I have created a dynamic model for filtering in vue 3 and have some problem when clear (empty the object)

 setup() {
    const model = ref({});

    watch(model.value, (value) => {
      console.log("model changed");
      console.log(model.value);
    });

    const addLanguage = (language) => {
      model.value["meta_"   language.toLowerCase()] = language;
    };

    const clear = () => {
      model.value = {};
    };

    return {
      addLanguage,
      clear,
    };
  },

I have also created a sample here for test https://codesandbox.io/s/mystifying-chebyshev-9tjogk?file=/src/App.vue

Adding new element to the model... the watcher is triggered .... but when you clear the object (empty) the watch function is no more triggered.

Any idea why ?

CodePudding user response:

The watch source (i.e., model.value) gets replaced in clear() with an empty object, so the watcher no longer gets triggered.

Solution

  1. Instead of unwrapping the model ref, pass the ref itself as the watch source.

  2. Pass the deep flag to the watch so that property addition/deletion is observed.

watch(
  model, 1️⃣
  (value) => { /* handle change */ },
  { deep: true } 2️⃣
)

demo

  • Related