vue 设置style 失效原因

设置notify的宽度时,发现在style中设置el-notification失效了

html 复制代码
<script>
    ...
    this.$notify({
        ...
    })
    ...
</script>
<style lang="scss" scoped>
.el-notification {
    width: 500px;
}
</style>

一开始考虑是优先级的问题,加了important尝试

html 复制代码
<style lang="scss" scoped>
.el-notification {
    width: 500px !important;
}
</style>

还是不行,最后发现是scoped的问题

在style不加scoped 的情况下,样式会全局生效,编译后样式会添加到<style>标签中,作用于整个页面。

但是如果加了scoped (vue特有),样式仅作用于当前组件 ,编译时会保证样式不会泄露到其他组件,但是如果样式使用了this.notify或者this.message等teleport 方法,将DOM渲染到body时,这些DOM不在组件树中,scoped样式无法匹配到它们,因为没有唯一属性

解决方法:

1、去除scoped

html 复制代码
<script>
    ...
    this.$notify({
        ...
    })
    ...
</script>
<style lang="scss"> // 去除scoped
.el-notification {
    width: 500px;
}
</style>

2、在调用notify时传入customClass,此处也是需要在非scoped中定义

html 复制代码
<script>
    ...
    this.$notify({
        customClass: 'notify-500'
        ...
    })
    ...
</script>
<style lang="scss"> // 去除scoped
.notify-500 {
    width: 500px;
}
</style>