亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 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 關注
  • 225 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號