Vue js 加载器覆盖全局 css

Vue js loader override global css

我想用 vue-loader 组件中定义的 css 覆盖全局 css。

目前我在 index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Dashboard</title>
    <link rel="stylesheet" href="build/styles.css">
</head>
<body id="the-dashboard">
<div id="app">

</div>


//......  Other Code Goes Here ......//
</body>
</html>

在我的 vue 组件中,我有一个作用域样式:

<template>
  // ..... Some Code Here ..... //
</template>

<style scoped>
   // ... css code here ... //
</style>
<script>
   // ... script goes here ... //
</script>

我想要的是当加载这个组件时,它应该完全覆盖 index.html 中的全局 css。也就是说,它的行为方式应该是只有作用域 css 应该适用于整个 body(index.html 中导入的 css 应该根本不用)。

这可能吗?

不,这不可能。

您可以将所有全局样式包装在某个选择器中,然后将您的 HTML 重构为您的组件,不要在其中。

.global {
  .someClass {
     ...
  }

  .another {

  }
}

<div class="global">
   <div class="someClass">
   ...
</div>

<component>
   <div class="someClass">
   ...
</component>

或者您也可以尝试创建一个 'global' 组件,然后在其中使用 Sass @import 导入 CSS,它将被内联包含。然后你把标签放在范围内(我不确定这是否适用于其中的子组件)。即:

<style scoped>
  @import 'build/main.css';
</style>

实际上最好的解决方案是:如果您不希望 CSS 成为全局的,则不要将其编码为全局的。使用 类 而不是通用标签名称和属性选择器。