[Vuejs]-Replacing an object without losing reactivity with Vue 3 (composition API)

3๐Ÿ‘

โœ…

I have finally solved the problem, so I will describe the solution.

I created a small example : https://codesandbox.io/s/wandering-paper-o952k?file=/src/App.vue

<template>
  <h1>{{ currentTime.toString() }}</h1>
  <button @click="currentTime = addMonths(1, currentTime)">
    Add one month
  </button>
</template>

function addMonths(numberOfMonths, currentTime) {
  const x = currentTime.getDate();
  currentTime.setMonth(currentTime.getMonth() + numberOfMonths);
  console.log(`Function has been called with : ${currentTime}`);
  if (currentTime.getDate() !== x) {
    currentTime.setDate(0);
  }
  return currentTime;
}

Vue is unable to detect the change because I return an object that has the same reference (as the old object). The solution is therefore to create a new object, in order to allow the change to be detected.

Insead of return currentTime;, do something like this return new Date(currentTime) will work.

Iโ€™m glad If I could help. Iโ€™ve been looking for the solution for a long time

Leave a comment