样式的作用域
在默认情况下,style中定义的样式将被应用于所有的组件上,但有些时候并不想这样,这个时候就需要使用样式的作用域了。
** style scoped **: 定义的样式只对当前组件有效。在Vue的实现中,会为HTML属性添加一个随机属性,比如:
<div data-v-201de89c>
同时,在scoped样式中的类也会被更改为类似这样的:
div[data-v-201de89c] {
// ...
}
但需要注意:如果过度使用这种scoped样式,会影响应用性能。更为简单而不影响性能的方式是让样式定义更具有针对性,比如:
.contact-form div {
// ...
}
同时需要注意,就算声明了scoped,也会影响到子元素的根元素样式:
With scoped, the parent component’s styles will not leak into child components. However, a child component’s root node will be affected by both the parent’s scoped CSS and the child’s scoped CSS. This is by design so that the parent can style the child root element for layout purposes.
当使用slot时,就算在父元素中声明的HTML元素最终会被嵌入子元素,但其样式将会受到父元素中样式定义的影响,而不是子元素中样式的影响。
全局作用域的样式
如果想要使用一些全局样式,可以在单独的文件中声明,比如:assets/global.css:
body {
// ...
}
h1 {
// ...
}
然后在main.js中引用:
import './assets/global.css'