千萬里不及你
2023-10-14 16:06:04
我正在嘗試使用按鈕來更新 Vue 中對象的屬性。該對象由 AJAX 查詢返回到數據庫,然后isFetching將布爾值設置為false,這會將包含的 div 附加到 DOM。當我嘗試更新屬性時,出現以下錯誤:TypeError: Cannot read property '_wrapper' of undefined下面是我的 AJAX 代碼:axios.post("/api/myEndpoint", { id: router.currentRoute.query.id }) .then((response) => { this.activities = response.data.activities; this.isFetching = false; }) .catch((errors) => { console.log(errors); router.push("/"); }); 這是我的 HTML:<div v-if="isFetching"> <h2>Loading data...</h2></div><div v-else> <div class="row no-gutters"> <div class="col"> <div class="d-flex flex-row justify-content-center"> <h4>Activities</h4> </div> <div class="custom-card p-2"> <div class="row no-gutters pb-4" v-for="(activity, index) in activities" :key="activity.stage_id"> <button v-if="!activity.is_removed" class="btn custom-btn" :class="{'hov': index == 0}" :disabled="index != 0" @click="markRemoved(activity)">Remove</button> </div> </div> </div> </div></div>最后,這是markRemoved()由按鈕的單擊偵聽器調用的:markRemoved(a) { a.is_removed = true;}當我嘗試登錄時,a對象markRemoved()會很好地記錄到控制臺,完全符合預期。is_removed在調試器中單步調試它后,在我嘗試更新對象的屬性時拋出異常。有誰知道我在這里做錯了什么?注意:我傳遞給AJAX查詢的id是Vue Router的查詢參數。這也設置正確并按預期通過。這是一個示例activity對象:{date_time_due: "2020-12-09T11:43:07.740Z" date_time_reached_stage: "2020-12-02T11:43:07.740Z" is_complete: true is_removed: false selected_option: "Some text" stage_id: 1 stage_name: "Some text"}僅在第一次單擊按鈕時引發異常。
1 回答

Cats萌萌
TA貢獻1805條經驗 獲得超9個贊
發布以防其他人將來遇到此錯誤。
Vue 只需要單文件組件標簽中的一個根元素<template>。我已經忘記了這一點,在我的例子中,有兩個<div>元素,一次顯示一個,有條件地使用 v-if:
<template>
<div v-if="fetchingData">
<h2>Loading data...</h2>
</div>
<div v-else>
<!-- The rest of the component -->
</div>
</template>
這導致了 Vue 的反應性問題,每當我嘗試更新組件的某些部分時就會拋出錯誤。意識到自己的錯誤后,我將所有內容都包裹在 root 中<div>。這為我解決了這個問題:
<template>
<div id="fixedComponent">
<div v-if="fetchingData">
<h2>Loading data...</h2>
</div>
<div v-else>
<!-- The rest of the component -->
</div>
</div>
</template>
添加回答
舉報
0/150
提交
取消