如何在Vue.js中为notify通知组件添加自定义样式
Vue.js Notify通知自定义样式不生效解决方案
第一步:修正自定义类传参参数名
你使用的classes是错误参数名,主流UI库的Notify通知自定义类参数如下:
- Element UI/Element Plus 系列:参数为
customClass - Ant Design Vue 系列:参数为
className
以Element系列为例,修正后的调用代码如下:
this.$notify({ title: '操作成功', message: '请求已成功保存', type: 'success', customClass: 'notfClas' })
第二步:解决样式作用域问题
Notify通知默认是挂载到页面根节点下的,不属于当前调用组件的DOM子树,如果你的自定义样式写在带scoped属性的组件样式块内,默认无法命中通知节点,有两种解决方式:
- 方案1:把样式写入全局样式文件,或项目入口组件(如App.vue)的无
scoped属性的style块中:
/* 全局样式中定义 */ .notfClas { background: #f0f9ff; border-radius: 8px; /* 其他自定义样式 */ } /* 修改通知内部标题样式 */ .notfClas .el-notification__title { color: #1e88e5; }
- 方案2:在带
scoped的组件样式块中使用深度选择器穿透作用域:
<style scoped> /* Vue3 写法 */ :deep(.notfClas) { background: #f0f9ff; } :deep(.notfClas .el-notification__content) { font-size: 14px; } /* Vue2 写法 */ ::v-deep .notfClas { background: #f0f9ff; } </style>
可选:提升样式优先级
如果自定义样式仍被UI库默认样式覆盖,可以通过增加选择器权重解决,例如:
/* 提高选择器优先级 */ .el-notification.notfClas { background: #f0f9ff !important; }
内容的提问来源于stack exchange,提问作者nsnclk
相关产品推荐
相关产品推荐

