You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js侧边栏未读通知计数:updated钩子还是computed更优?

Which is Better: updated() Hook or computed for Unread Notification Count in Sidebar?

Great question! Let’s break this down to figure out the best practice for your scenario:

Go with computed — it’s the ideal choice here

Here’s why this aligns with Vue’s best practices:

  • Dependency-driven & cached: Computed properties automatically track their reactive dependencies (in your case, the list of notifications fetched from the API). It only re-runs the count logic when the notification list changes (e.g., new notifications arrive, a notification is marked as read). No unnecessary repeated calculations!
  • Clean & declarative: It directly represents derived data (unread count) from your source data (notification list), making your code easier to read and maintain. You don’t have to manually trigger updates — Vue handles it for you.

Example Implementation

<template>
  <aside class="sidebar">
    <span class="unread-badge">{{ unreadNotificationCount }}</span>
    <!-- Rest of sidebar content -->
  </aside>
</template>

<script>
export default {
  data() {
    return {
      notifications: [] // Reactive list of notifications from API
    };
  },
  async created() {
    // Fetch notifications when component is created
    const apiResponse = await this.$http.get("/notifications");
    this.notifications = apiResponse.data;
  },
  methods: {
    async markNotificationAsRead(notificationId) {
      // Update notification status via API
      await this.$http.patch(`/notifications/${notificationId}`, { viewed: true });
      // Update local reactive list to trigger computed update
      this.notifications = this.notifications.map(notification => 
        notification.id === notificationId 
          ? { ...notification, viewed: true } 
          : notification
      );
    }
  },
  computed: {
    unreadNotificationCount() {
      // Calculate unread count only when notifications change
      return this.notifications.filter(n => !n.viewed).length;
    }
  }
};
</script>

Why updated() is not a good fit

The updated() hook triggers every single time your component re-renders — even when the change has nothing to do with notifications (e.g., a unrelated prop updates, a different data property changes). This leads to:

  • Unnecessary performance overhead: You’ll run the count logic (and potentially re-fetch from the API) far more often than needed.
  • Risk of infinite loops: If your count logic accidentally modifies component state, it could trigger another re-render, creating a loop.
  • Less maintainable code: Mixing data computation with post-render logic breaks the separation of concerns in Vue.

内容的提问来源于stack exchange,提问作者Olga B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:40:03