Home > Blockchain >  VueJs3 Data Object is not being updated via Watcher
VueJs3 Data Object is not being updated via Watcher

Time:07-05

M1y aim is to fill this empty reactive data property with an object from my store.

let matchedFile = reactive({});

I return an object from my store below

const matchedFiles = computed(() => {
  return store.activeFile;
});

I watch the above computed

watch(matchedFiles, async (newVal) => {
  updateMatchedF(newVal);
});

Which in turn calls the following method:

function updateMatchedF(val) {
      matchedFile = val;
    }

Object being passed (proxy)

    {
    "name": "Hello World",
    "id": 12311,
    "title": "test file"
    }

For some reason, the object is succesfully passed to the very last method, and console.log even shows a succesful update. But VueTools shows an empty object. What am I not doing right here?

CodePudding user response:

There's no way how a variable can be reactive when it's reassigned like matchedFile = val. In this case it should be a ref and change a reference at some point.

Also if there's a chance that watched value is available at the time when the component is instantiated, the watcher should be immediate.

It's preferable to use null instead of empty object to distinguish empty value:

const matchedFile = ref(null);

watch(matchedFiles, async (newVal) => {
  updateMatchedF(newVal);
}, { immediate: true });

function updateMatchedF(val) {
  matchedFile.value = val;
}
  • Related