As is stated in this answer, you can't define separate CSS in a Vue component using something like css like you can define HTML using template.
话虽如此,有几种方法可以为特定组件/元素定义 CSS:
作用域 CSS
您可以将style 定义为一个组件:
App.vue
<template>
<div id="app">
<RedComponent/>
<NotRedComponent/>
</div>
</template>
<script>
import RedComponent from "./components/RedComponent";
import NotRedComponent from "./components/NotRedComponent";
export default {
components: {
RedComponent,
NotRedComponent
}
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
RedComponent.vue
<script>
export default {
template: "<div>I am red</div>"
};
</script>
<style scoped>
div {
color: red;
}
</style>
NotRedComponent.vue
<script>
export default {
template: "<div>I am not red</div>"
};
</script>
See this live here
CSS 类和 ID
您可以给元素类和 ID 以便使用 CSS 选择它们,并且只需要一个单独的 CSS 文件。注意:这不是 Vue 独有的。
App.vue
<script>
export default {
name: "App",
template: '<div><p class="red">I am red</p><p>I am not red</p></div>'
};
</script>
index.css
.red {
color: red;
}
See this live here
您可以从任何地方(在合理范围内)引用此 index.css 文件 - 例如,在我的现场演示中,它是从 index.html 本身内引用的(类似于 <head> 标记中的 <link rel="stylesheet" type="text/css" href="index.css" /> 即可)。
内联样式
为此,使用反引号 (`) 而不是引号将使您的生活更轻松。使用反引号的另一个好处是您可以将模板跨越多行。
App.vue
<script>
export default {
name: "App",
template: `<div>
<p style="color: red">I am red</p>
<p>I am not red</p>
</div>`
};
</script>
See this live here
就我个人而言,我从来没有发现一个使用范围 CSS 无法解决问题的用例,即使使用 vue-router 也是如此,但如果您出于任何原因无法使用它,这些是一些替代选项。