使用 Vue 3(组合 API)替换对象而不失去反应性

我想更新我的对象并保持反应性。selectedTime是一个 Date 对象,substractMonths将返回一个新的 Date 对象。


<span

   class="calendar__pickable__chevron"

   @click="selectedTime = substractMonths(1, selectedTime)"

   >

   <span>

      <font-awesome-icon icon="chevron-left" />

   </span>

</span>

问题是,通过这样做,我的状态没有更新,因为 Vue 3 无法检测到对象的替换。


我该如何解决这个问题呢?(我指定我已经用来const selectedTime = ref(new Date())创建反应式对象)。

https://img1.mukewang.com/651543c8000116b206470348.jpg

Subtract 函数确实返回新Date对象。

部分代码:https://gist.github.com/SirMishaa/efb0efe74c6355aabbcb853f7650c22f

我唯一尝试做的就是执行一个返回新日期的函数,并将 my 替换selectedTime为该函数的返回值。


慕容3067478
浏览 94回答 1
1回答

月关宝盒

我终于解决了这个问题,所以我将描述解决方案。我创建了一个小示例:https ://codesandbox.io/s/wandering-paper-o952k?file=/src/App.vue<template>&nbsp; <h1>{{ currentTime.toString() }}</h1>&nbsp; <button @click="currentTime = addMonths(1, currentTime)">&nbsp; &nbsp; Add one month&nbsp; </button></template>function addMonths(numberOfMonths, currentTime) {&nbsp; const x = currentTime.getDate();&nbsp; currentTime.setMonth(currentTime.getMonth() + numberOfMonths);&nbsp; console.log(`Function has been called with : ${currentTime}`);&nbsp; if (currentTime.getDate() !== x) {&nbsp; &nbsp; currentTime.setDate(0);&nbsp; }&nbsp; return currentTime;}Vue 无法检测到更改,因为我返回一个具有相同引用(与旧对象)的对象。因此,解决方案是创建一个新对象,以便检测到更改。相反return currentTime;,做这样的事情return new Date(currentTime)会起作用。如果我能帮忙的话我很高兴。我已经寻找解决方案很长时间了
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript