如何在 Vue.js 中使用 /deep/ 或 >>> 或 ::v-deep?

新手上路,请多包涵

所以,我在 这里 读到,在 Vue.js 中,您可以在选择器中使用 /deep/>>> 以创建适用于子组件内部元素的样式规则。但是,尝试在我的样式中使用它,无论是在 SCSS 中还是在普通的旧 CSS 中,都行不通。相反,它们被逐字发送到浏览器,因此没有效果。例如:

家.vue:

 <style lang="css" scoped>
.autocomplete >>> .autocomplete-input
{
// ...
}
</style>

生成的CSS:

 <style type="text/css">
.autocomplete >>> .autocomplete-input[data-v-2bda0c9a]
{
//...
}
</style>

我想要的是:

 <style type="text/css">
.autocomplete[data-v-2bda0c9a] .autocomplete-input
{
//...
}
</style>

我与 vue-loader 相关的 webpack 配置如下所示:

 // ...
{
    test: /\.vue$/,
    loader: "vue-loader",
    options: {
        loaders: {
            scss: "vue-style-loader!css-loader!sass-loader"
        }
    }
}
// ...

所以我的问题是,我如何让这个 >>> 运算符工作?

我已经找到 了这个 答案,但我正在这样做,但它不起作用……

原文由 laptou 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

Vue 2

以下内容也适用于 Vue 3,但已弃用。

Sass: 使用 ::v-deep

 ::v-deep .child-class {
    background-color: #000;
}

使用 Sass: 使用 >>>

 >>> .child-class {
    background-color: #000;
}

无论使用哪种语法,该组件的 <style> 标记都必须是 scoped

 <style scoped>


Vue 3 (2022 年 7 月 14 日更新)

在 Vue 3 中, ::v- 前缀现已 弃用,我们不再需要 >>>无论是否使用 Sass ,我们都可以使用统一的 :deep 选择器,但现在建议在选择器上使用括号。

使用 :deep(.child-class)

 :deep(.child-class) {
    background-color: #000;
}

这也适用于 Vue 2.7(最终的 Vue 2 版本)


Vue 3 新的选择器

此外,在 Vue 3 中,具有 <slot> 的组件有一个 新功能,可以启用样式传递的插槽内容。

插槽内容 使用 :slotted(.child-class)

 :slotted(.slot-class) {
    background-color: #000;
}

最后,在 Vue 3 中,甚至可以从 — scoped 组件注册全局样式:

全局样式 使用 :global(.my-class)

 :global(.my-class) {
    background-color: #000;
}

对于任何语法,该组件的 <style> 标记必须是 scoped

 <style scoped>


概括

在 Vue 2 中:

  • /deep/ 语法已弃用
  • 使用 ::v-deep 与 Sass,使用 >>> 没有 Sass

在 Vue 3 中:

  • ::v-deep .child-class 已弃用,取而代之的是 :deep(.child-class)
  • ::v- 前缀已被弃用,取而代之的是 :
  • >>> 语法已弃用
  • /deep/ 语法已弃用
  • 有新的 :slotted:global 选择器

对于每个版本/语法,该组件的 <style> 标签必须是 scoped

 <style scoped>

原文由 Dan 发布,翻译遵循 CC BY-SA 4.0 许可协议

避免使用 /deep/ 而是使用 ::v-deep

任何作用域 component's css 可以通过使用 deep selector 更改,但更快 /deep/ 将被弃用

Vue Github 参考 - https://github.com/vuejs/vue-loader/issues/913

在这种情况下 使用 ::v-deep ,并避免弃用 /deep/

参考 - 深度选择器

只需检查要在 chrome 或任何浏览器控制台中使用 devtools 修改的渲染类 element

然后,在你消费 component ,修改它

<style scoped>
::v-deep .custom-component-class {
   background: red; //
}
</style>

原文由 Satyam Pathak 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题