vue3使用深度选择器修改样式
解决警告:
[@vue/compiler-sfc] the >>> and /deep/ combinators have been deprecated. Use :deep() instead.
vue3已弃用以往的深度选择器
警告: the >>> and /deep/ combinators have been deprecated. Use :deep() instead. 翻译过来就是 [>>>和/deep/已经被弃用。使用方法:deep()。] 虽然以往的>>>和/deep/依然可以使用,但是会出现警告语句提示 要是不想看到警告的话可以使用 [:deep()] 即可例子:
/deep/ .el-button.is-round {
? ? padding: 4px 20px;
? ? background-color: #109cf1;
}
/*改为如下书写方式即可 */
:deep(.el-button.is-round) {
? ? padding: 4px 20px;
? ? background-color: #109cf1;
}
当有并集选择器,直接把类名放入 :deep() 括号中是不太对的:
/*如下修改只能改到第一个类名,修改不到第二个类名 */
:deep(.el-input__inner,
.el-button.is-round) {
? ? width: 440px;
? ? height: 60px;
? ? line-height: 20px;
? ? border-radius: 30px;
? ? border: 1px solid rgba(211, 211, 211, 100);
? ? font-size: 16px;
}
/*应改为 */
:deep(.el-input__inner),
:deep(.el-button.is-round) {
? ? width: 440px;
? ? height: 60px;
? ? line-height: 20px;
? ? border-radius: 30px;
? ? border: 1px solid rgba(211, 211, 211, 100);
? ? font-size: 16px;
}
vue如何使用深度选择器?
在作用域 css 中,如果您需要使用深度选择器(即来自父作用域 css)修改子组件的样式,那么您需要使用>>>组合器。
例如,父作用域 css 上的作用域深度选择器如下所示,
<style scoped>
.class1 >>> .class2 { /* ... */ }
</style>
它将被转换为,
.class1[data-v-f3f3eg9] .class2 { /* ... */ }
注意:如果您使用 SASS 等预处理器,则它可能无法正确处理 >>>。在这种情况下,使用 /deep/ 或 ::v-deep 组合器代替 >>> 组合器。
父样式是否泄漏到作用域 css 中的子组件中?
父组件的样式不会泄漏到子组件中。但是子组件的根节点会同时受到父级作用域 CSS 和子级作用域 CSS 的影响。即,您的子组件的根元素有一个类也存在于父组件中,父组件的样式将泄漏给子组件。无论如何,这是设计使然,以便父级可以为子根元素设置样式以用于布局目的。
例如,父组件的背景颜色属性泄漏到子组件中,如下所示,
//parent.vue
<template>
? <div class="wrapper">
? ? <p>parent</p>
? ? <ChildMessageComponent/>
? </div>
</template>
<script>
import ChildMessageComponent from "./components/child";
export default {
? name: "App",
? components: {
? ? ChildMessageComponent
? }
};
</script>
<style scoped>
.wrapper {
? background: blue;
}
</style>
//child.vue
<template>
? <div class="wrapper">
? ? <p>child</p>
? </div>
</template>
<script>
export default {
? name: "Hello, Scoped CSS",
};
</script>
<style scoped>
.wrapper {
? background: red;
}
</style>
现在子包装器的背景颜色将变为蓝色而不是红色。
如何在 vuejs 中使用 CSS 模块?
以下是在 VueJS 中使用 css 模块的步骤,
启用 CSS 模块: CSS 模块必须通过将 modules: true 选项传递给 css-loader 来启用
// webpack.config.js
{
? module: {
? ? rules: [
? ? ? // ... other rules omitted
? ? ? {
? ? ? ? test: /\.css$/,
? ? ? ? use: [
? ? ? ? ? 'vue-style-loader',
? ? ? ? ? {
? ? ? ? ? ? loader: 'css-loader',
? ? ? ? ? ? options: {
? ? ? ? ? ? ? // enable CSS Modules
? ? ? ? ? ? ? modules: true,
? ? ? ? ? ? ? // customize generated class names
? ? ? ? ? ? ? localIdentName: '[local]_[hash:base64:8]'
? ? ? ? ? ? }
? ? ? ? ? }
? ? ? ? ]
? ? ? }
? ? ]
? }
}
添加模块属性:将模块属性添加到您的<style>
<style module>
.customStyle {
? background: blue;
}
</style>
注入 CSS 模块:您可以使用计算属性 $style 注入 CSS 模块对象
<template> ? <div :class="$style.blue"> ? ? Background color should be in blue ? </p> </template>
它可以使用 :class 绑定的对象/数组语法。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
查看更多关于vue3使用深度选择器修改样式问题的详细内容...