vue.js - 组件的 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 组件中定义单独的 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 也是如此,但如果您出于任何原因无法使用它,这些都是一些替代选项。
推荐阅读
- google-cloud-speech - Google 语音转文本 API 密钥无效
- google-oauth - 向 G-Suite 、服务帐户的 OAuth 或服务器端 Web 应用程序的 OAuth 进行身份验证的最佳方法是什么
- sql-server - 升级 SQL Server 版本后出现问题,现在 services.msc 中有两台服务器
- javascript - 如何修复 Ajax 调用“参数字典包含一个空条目......”
- jquery - 同一日期但不同月份的月差
- c# - LINQ 执行流程(作业)
- assembly - MOVMSKB 操作有什么用?
- javascript - 将 Nuxt 迁移到 2.7:刷新循环
- javascript - 元素隐式具有“任何”类型,因为类型“xxx”没有索引签名。ts(7017)
- angular - 获取角度 Firestore 中的所有集合?