繁体   English   中英

带有过滤器的VueJS反应阵列

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM