【问题标题】:Vue js loader override global cssVue js 加载器覆盖全局 css
【发布时间】:2023-04-11 05:18:01
【问题描述】:

我想用 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 应该是应用于整个主体的 css(根本不应该使用在 index.html 中导入的 css)。

这可能吗?

【问题讨论】:

  • &lt;style scoped&gt; 应该这样做吗?如果您的主要 css 文件类也存在于 &lt;style scoped&gt; 中,它应该被覆盖了吗?
  • 它似乎覆盖了这一点。但是存在许多在全局 CSS 中定义的其他属性。覆盖作用域 css @AmreshVenugopal 中的所有内容是不切实际的
  • 哦,所以你只想让 scoped 中的样式生效?
  • @AmreshVenugopal 没错!
  • 我似乎有一个解决方案,不知道它有多糟糕。 import 组件中的 css 重置文件。

标签: javascript html css vuejs2 vue-loader


【解决方案1】:

不,这不可能。

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

.global {
  .someClass {
     ...
  }

  .another {

  }
}

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

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

或者你也可以尝试创建一个“全局”组件,然后在其中使用 Sass @import 导入 CSS,它将被内联。然后你把标签作为作用域(我不确定这是否适用于其中的子组件)。那就是:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 2014-09-27
    • 2021-01-21
    • 2021-05-07
    相关资源
    最近更新 更多