gpt4 book ai didi

javascript - 为什么vue中的作用域样式没用?父元素样式仍然影响子元素

转载 作者:行者123 更新时间:2023-11-29 23:28:59 25 4
gpt4 key购买 nike

父元素样式:

.container {
margin: 20px;
border:1px solid #f1f1f1;
font-size:14px;
font-weight:normal;

子元素样式:

.container{}

但是子元素样式应该这样渲染:

enter image description here

为什么子元素中有两个data-v-***,并使用父容器样式?

最佳答案

我知道已经很久了,但我要在这里添加一些内容以帮助 future 的人。

我遇到了同样的事情。基本上,我将组件嵌套在组件中,并且非常喜欢 scoped 以便每个组件都有一个名为 .container 的类......在呈现样式时令我惊讶开始矛盾了我认为 scoped 是为了解决这个问题......

但显然是设计使然,事实并非如此:

https://vue-loader.vuejs.org/guide/scoped-css.html#mixing-local-and-global-styles

With scoped, the parent component's styles will not leak into child components. However, a child component's root node will be affected by both the parent's scoped CSS and the child's scoped CSS. This is by design so that the parent can style the child root element for layout purposes.

例如,我有两个嵌套的组件,我最终得到的是:

enter image description here

我有一个 View 在两个组件中加载:

<template>
<div>
<login-splash />
<login-form />
</div>
</template>

包含的两个是这样的:

<template>
<div class="container">
<div>
<h1 class="big">Title</h1>
<h2 class="small">Subtitle</h2>
</div>
</div>
</template>

<template>
<div class="container">
<form class="form">
<label class="label">Username
<input class="input" type="input" name="username">
</label>
<label class="label">Password
<input class="input" type="password" name="password">
</label>
<a href="" class="link">Forgot Password</a>
</form>
<button-submit />
</div>
</template>

问题出在 button-submit 上,如下所示:

<template>
<div class="container">
<button class="button">Button</button>
</div>
</template>

这些文件中的每一个都有 scoped SCSS,它最终会产生上述问题。

这所有的阶梯都回到https://v2.vuejs.org/v2/style-guide/#Component-style-scoping-essential

基本上,解决方案是“使用像 bem 这样基于类命名的解决方案”……这不是任何人在看到和使用 scoped 时想听到的,并认为它是银弹。 .我知道......但是对于所有网络开发,你必须做你必须做的事。

If you are developing a large project, working with other developers, or sometimes include 3rd-party HTML/CSS (e.g. from Auth0), consistent scoping will ensure that your styles only apply to the components they are meant for.

Beyond the scoped attribute, using unique class names can help ensure that 3rd-party CSS does not apply to your own HTML. For example, many projects use the button, btn, or icon class names, so even if not using a strategy such as BEM, adding an app-specific and/or component-specific prefix (e.g. ButtonClose-icon) can provide some protection.


另一种方法是使用 CSS 模块,如本回答所述: https://stackoverflow.com/a/45900067/1034494

这最终会产生这样的东西: enter image description here

关于javascript - 为什么vue中的作用域样式没用?父元素样式仍然影响子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47985700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com