使用 Vue 3 替换对象而不失去反应性(组合 API)
Replacing an object without losing reactivity with Vue 3 (composition API)
我想更新我的对象并保持反应性。 selectedTime
是一个 Date 对象,substractMonths
将 return 一个新的 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())
创建了一个反应对象)。
减法函数执行 return 新的 Date
对象。
部分代码:https://gist.github.com/SirMishaa/efb0efe74c6355aabbcb853f7650c22f
我唯一尝试做的就是执行一个 return 新日期的函数,并将我的 selectedTime
替换为 的 return 值功能。
我终于解决了问题,所以我将描述解决方案。
我创建了一个小例子: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 一个对象具有相同的引用(作为旧对象)。因此,s解决方案是创建一个新对象,以便能够检测到更改。
Insead return currentTime;
,做这样的事情 return new Date(currentTime)
会奏效。
很高兴能帮上忙。找了好久
我想更新我的对象并保持反应性。 selectedTime
是一个 Date 对象,substractMonths
将 return 一个新的 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())
创建了一个反应对象)。
减法函数执行 return 新的 Date
对象。
部分代码:https://gist.github.com/SirMishaa/efb0efe74c6355aabbcb853f7650c22f
我唯一尝试做的就是执行一个 return 新日期的函数,并将我的 selectedTime
替换为 的 return 值功能。
我终于解决了问题,所以我将描述解决方案。
我创建了一个小例子: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 一个对象具有相同的引用(作为旧对象)。因此,s解决方案是创建一个新对象,以便能够检测到更改。
Insead return currentTime;
,做这样的事情 return new Date(currentTime)
会奏效。
很高兴能帮上忙。找了好久