[英]VueJS Reactive Array with filters
我有一個帶有兩個過濾器的通知列表(“全部顯示”,“顯示未讀”)。 創建組件時,我會加載所有通知,然后調用篩選器“顯示全部”。
created() {
axios.get('user/notifications').then(response => {
this.notifications = response.data;
this.showAll();
}).catch(e => {
console.log(e);
});
},
這是“顯示全部”和“顯示未讀”方法:
showAll() {
this.filteredNotifications = this.notifications;
},
showUnread() {
this.filteredNotifications = _.filter(this.notifications, notif => {
return notif.read_at === null;
});
},
我正在像這樣迭代數組:
<li v-for="notif in filteredNotifications">
<span @click="toggleNotification(notif)"></span>
</li>
在這里,我切換通知:
toggleNotification(notification) {
axios.put('user/notification/' + notification.id + '/toggle', {_method: 'PUT'}).then(response => {
notification.read_at = notification.read_at == null ? true : null;
}).catch(e => {
console.log(e);
});
}
我正在嘗試做到這一點,當我進入“顯示未讀”過濾器時,每當我切換通知時,它將從該過濾器中刪除。 無法將其從原始陣列中刪除,因為當我單擊“全部顯示”時,我必須查看所有通知。
目前,當我進入“查看未讀的過濾器”時,如果我切換通知,它將通知read_at
更改為true,但不會將其從列表中刪除。 只有當我再次單擊過濾器時,它才會刷新。
我可以通過在每個過濾器中放置一個標志來輕松解決此問題,然后在toggleNotification中可以檢查哪個標志處於活動狀態並手動調用它的方法,但這對我來說太臟了。 有什么幫助嗎?
您的方法看起來還可以。 但是,如果要通知標記為已讀,則將請求發送到后端數據庫以設置read_at = currentDate。 當請求成功結束時,只需從this.filteredNotifications數組中按其索引排除讀取通知,Vue將根據新數組重新呈現。
<li v-for="(notif, index) in filteredNotifications">
<span @click="toggleNotification(notif, index)"></span>
</li>
然后在您的方法中:
toggleNotification(notification, index) {
axios.put('user/notification/' + notification.id + '/toggle', {_method: 'PUT'}).then(response => {
notification.read_at = notification.read_at == null ? true : null;
this.filteredNotifications.splice(index, 1)
}).catch(e => {
console.log(e);
});
如果要基於響應重新呈現,則在響應中發送回所有未讀的通知並設置this.filteredNotifications = response。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.