【问题标题】:Replacing an object without losing reactivity with Vue 3 (composition API)使用 Vue 3(组合 API)替换对象而不失去反应性
【发布时间】:2021-03-15 09:50:47
【问题描述】:

我想更新我的对象并保持反应性。 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()) 来创建反应对象)。

减法函数确实返回新的Date 对象。

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

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

【问题讨论】:

  • 你知道computed properties吗?您是否尝试将substractMonths(1, selectedTime) 提取到计算中?
  • 我正在使用composition API,这是如何使用它的?
  • @BoussadjraBrahim 为什么需要它?我只是在约会,我添加了选定的月数,然后返回新的日期。
  • 我认为我不需要计算方法,我只是想改变我的状态。我做了一个日期选择器,用于上下文。
  • @Misha 可能是 stackoverflow.com/questions/40959483/… 的副本。您的日期函数会修改原始日期并将其返回。由于对selectedTime 的引用没有改变,Vue 没有检测到它,所以模板没有更新。一种解决方法是让您的日期函数从原始日期(我认为您可能打算开始)创建一个新日期。 codesandbox.io/s/updating-date-object-in-template-9nmlj?file=/…

标签: javascript typescript vue.js vuejs3


【解决方案1】:

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

我创建了一个小例子: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) 的操作会起作用。

如果我能提供帮助,我很高兴。找了很久的解决办法

【讨论】:

    猜你喜欢
    • 2021-04-20
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 2021-02-11
    • 2021-07-11
    • 1970-01-01
    相关资源
    最近更新 更多