如何使用switch语句根据通知类型切换通知图标?
Got it, let's get this working exactly how you want—using a switch statement instead of conditional checks to swap icons based on your notification types. Here's a step-by-step breakdown:
1. Update Your Template
First, we'll dynamically bind the icon's class to a method that returns the correct icon class based on the notification type. Modify the <i> tag in your existing code to use Vue's :class directive:
<div class="media g-mb-20"> <span class="u-icon-v3 g-rounded-50x g-mt-2 g-mr-15 g-height-40 g-width-40 g-bg-gray-light-v5"> <!-- Dynamically bind the icon class here --> <i :class="getNotificationIcon(item.type)" class="g-font-size-18 g-color-gray-light-v1"></i> </span> <a href="#" class="media-body g-brd-around g-brd-gray-light-v4 g-py-10 g-px-15 g-bg-gray-light-v5--hover u-link-v5 g-rounded-3"> <p class="mb-0 g-font-size-16 g-color-gray-dark-v3"> <span class="g-font-stag-medium">{{ item.message }}</span> </p> </a> </div>
2. Add the Switch Statement in a Method
Next, define a method in your Vue component that uses a switch statement to map each notification type to its corresponding icon class. Replace the placeholder icon classes (like icon-bubble) with your actual icon class names:
export default { // ... other component options (data, props, etc.) methods: { getNotificationIcon(notificationType) { switch(notificationType) { case 'answer_created': return 'icon-bubble'; // Replace with your "answer created" icon class case 'user_subscribed': return 'icon-user-follow'; // Replace with your "user subscribed" icon class case 'answer_selected': return 'icon-check-circle'; // Replace with your "answer selected" icon class default: return 'icon-bubble'; // Fallback icon if type is unrecognized } } } }
How This Works
- The
:classdirective on the<i>tag callsgetNotificationIcon(item.type)every time the component renders, passing in the notification type from youritemobject. - The
switchstatement checks the incoming type and returns the exact icon class you need—no messyif/elsechains required. - The
defaultcase ensures you have a fallback icon if an unexpected type comes through.
Note on Your Original Idea
You mentioned binding to the <span> with v-bind="changeIcon"—while that's possible (by having the method return an object with attributes for the span), it's more straightforward to bind directly to the <i> tag since that's where the icon lives. The approach above keeps your code clean and focused on the element that actually needs the dynamic class.
内容的提问来源于stack exchange,提问作者Olga B

