Vue.js中仅保留最高优先级通知类的标记问题
Vue通知图标优先级类名渲染问题修复
需求说明
通知分为三类,优先级从高到低为:error(红色)> warning(橙色)> success(绿色)。图标需根据最高优先级的通知着色,多类型通知共存时,仅保留最高优先级对应的类名,而非所有匹配类。
原代码问题
原computed属性iconClasses会同时返回所有匹配的类名,导致多类型共存时图标类混乱,例如同时出现has-success has-warning has-error,不符合需求。
原代码:
<button> <span class="Icon name_notification" :class="iconClasses" ></span> </button> <script> export default { computed: { iconClasses() { const { notifications } = this; return { indication: !!notifications.length, 'has-success': notifications.findIndex(({options}) => options.type === 'success') !== -1, 'has-warning': notifications.findIndex(({options}) => options.type === 'warning') !== -1, 'has-error': notifications.findIndex(({options}) => options.type === 'error') !== -1, }; }, }, } </script>
尝试方案的错误分析
方案1错误点
- 优先级判断逻辑错误:数组中使用类名
has-error,但通知类型是error,两者不匹配,导致topPriority始终为undefined。 - 对象属性赋值错误:直接写
topPriority会将键名设为字符串topPriority,而非变量对应的值,正确写法应为[topPriority]: true(但前提是topPriority能正确获取)。
方案2错误点
- 同样存在优先级判断逻辑错误,类名与通知类型不匹配,导致
topPriority为undefined,无法添加正确类名。 - 核心问题未解决,即便数组写法格式正确,也无法渲染出预期类名。
正确实现方式
方式一:返回对象(语义清晰,推荐)
通过优先级顺序判断,仅为最高优先级的类名设置true:
<button> <span class="Icon name_notification" :class="iconClasses" ></span> </button> <script> export default { computed: { iconClasses() { const { notifications } = this; const hasError = notifications.some(({ options }) => options.type === 'error'); const hasWarning = notifications.some(({ options }) => options.type === 'warning'); const hasSuccess = notifications.some(({ options }) => options.type === 'success'); const classes = { indication: !!notifications.length }; // 按优先级从高到低赋值 if (hasError) { classes['has-error'] = true; } else if (hasWarning) { classes['has-warning'] = true; } else if (hasSuccess) { classes['has-success'] = true; } return classes; }, }, } </script>
方式二:返回数组(更简洁)
直接构建类名数组,仅添加符合优先级的类:
<script> export default { computed: { iconClasses() { const { notifications } = this; const classes = []; if (notifications.length) { classes.push('indication'); // 优先判断高优先级类型 if (notifications.some(({ options }) => options.type === 'error')) { classes.push('has-error'); } else if (notifications.some(({ options }) => options.type === 'warning')) { classes.push('has-warning'); } else if (notifications.some(({ options }) => options.type === 'success')) { classes.push('has-success'); } } return classes; }, }, } </script>
两种方式都能确保:存在error时仅渲染has-error,存在warning无error时渲染has-warning,仅success时渲染has-success,同时保留indication类(当有通知时)。
内容的提问来源于stack exchange,提问作者Jul
相关产品推荐
相关产品推荐

