vue.js 中设置样式有四种方法:使用内联样式、局部(scoped)样式、sass/scss 预处理器以及 css 模块。内联样式直接写入模板;局部样式仅适用于当前组件;sass/scss 提供更强大的样式编写功能;css 模块生成唯一类名避免冲突。
Vue 中设置样式的方法
在 Vue.js 中,可以使用多种方法为组件和元素添加样式。
1. 内联样式
内联样式直接写入组件模板,是最简单的样式设置方法。
<code class="html"><template><div style="color: red; font-size: 20px;">Hello World</div> </template></code>
登录后复制
2. 局部样式(scoped)
scoped 样式仅适用于当前组件及其内部元素,可以防止样式污染。
<code class="html"><template><style scoped>
.my-class {
color: blue;
font-weight: bold;
}
</style>
<div class="my-class">Hello World</div>
</template></code>
登录后复制
3. Sass/SCSS
Sass 和 SCSS 是 CSS 预处理器,可以在 Vue.js 中使用来编写更强大的样式。
<code class="s<a style='color:#f60; text-decoration:underline;' href=" https: target="_blank">css">// main.scss
.my-component {
color: #f00;
font-size: 1.2rem;
}</code>
登录后复制
<code class="html"><template><style lang="scss">
@import "./main.scss";
</style>
<div class="my-component">Hello World</div>
</template></code>
登录后复制
4. CSS 模块
CSS 模块通过生成唯一的类名来防止样式冲突,通常与 webpack 一起使用。
<code class="javascript">// App.<a style="color:#f60; text-decoration:underline;" href="https://www.php.cn/zt/15721.html" target="_blank">vue</a>
import styles from './App.module.css';
export default {
render() {
return (
<div classname="{styles.myClass}">Hello World</div>
);
}
}</code>
登录后复制
<code class="css">// App.module.css
.myClass {
color: green;
text-align: center;
}</code>
登录后复制






