为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕容3067478 2023-09-28 17:11:42
我想更新我的对象并保持反应性。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())创建反应式对象)。Subtract 函数确实返回新Date对象。部分代码:https://gist.github.com/SirMishaa/efb0efe74c6355aabbcb853f7650c22f我唯一尝试做的就是执行一个返回新日期的函数,并将 my 替换selectedTime为该函数的返回值。
查看完整描述

1 回答

?
月关宝盒

TA贡献1772条经验 获得超5个赞

我终于解决了这个问题,所以我将描述解决方案。

我创建了一个小示例: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 无法检测到更改,因为我返回一个具有相同引用(与旧对象)的对象。因此,解决方案是创建一个新对象,以便检测到更改。


相反return currentTime;,做这样的事情return new Date(currentTime)会起作用。


如果我能帮忙的话我很高兴。我已经寻找解决方案很长时间了


查看完整回答
反对 回复 2023-09-28
  • 1 回答
  • 0 关注
  • 91 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信