首页 > 解决方案 > 组件的 vue.js 自定义 css(没有 webpack 和 vue-loader)

问题描述

使用 Vue Router 加载组件。

请注意,我没有使用 webpack 或 vue-loader。

这是一个由 vue 加载的示例组件 - 路由器

export default {
    name: 'Abc',
    template:'<div>Now .. i can't add style element here :(. So where should i add it </div>',
    data(){
        return {
             message:' new message'
        }
    },
}

我在哪里可以添加 css 样式。如果不可能,我不在乎css范围。

不想使用渲染函数(https://vuejs.org/v2/guide/render-function#The-Data-Object-In-Depth).. 因为创建 dom 结构会杀了我

标签: vue.jsvuejs2vue-router

解决方案


如本答案所述,您无法在 Vue 组件中定义单独的 CSS,css例如您可以使用template.

话虽如此,有几种方法可以为特定组件/元素定义 CSS:


作用域 CSS

您可以将 a 定义style为一个组件:

应用程序.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>

红色组件.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>

在这里直播


CSS 类和 ID

您可以提供元素类和 ID,以便使用 CSS 选择它们,并且只需一个单独的 CSS 文件。注意:这不是 Vue 独有的。

应用程序.vue

<script>
export default {
  name: "App",
  template: '<div><p class="red">I am red</p><p>I am not red</p></div>'
};
</script>

索引.css

.red {
  color: red;
}

在这里直播

您可以index.css从任何地方(在合理范围内)引用此文件 - 例如,在我的现场演示中,它是从index.html自身内部引用的(类似于<link rel="stylesheet" type="text/css" href="index.css" /><head>标签内的事情)。


内联样式

为此,使用反引号 (`) 而不是引号将使您的生活更轻松。使用反引号的另一个好处是您可以将模板跨越多行。

应用程序.vue

<script>
export default {
  name: "App",
  template: `<div>
    <p style="color: red">I am red</p>
    <p>I am not red</p>
  </div>`
};
</script>

在这里直播


就我个人而言,我从来没有发现一个使用范围 CSS 无法解决问题的用例,即使使用 vue-router 也是如此,但如果您出于任何原因无法使用它,这些都是一些替代选项。


推荐阅读