Vue.js 样式 v-html 范围 css

Vue.js style v-html with scoped css

如何使用 vue-loader 为 v-html 内容设置范围 css 的样式?

简单示例: component.vue

<template>
  <div class="icon" v-html="icon"></icon>
</template>
<script>
  export default {
    data () {
      return {icon: '<svg>...</svg>'}
    }
  }
</script>
<style scoped>
  .icon svg {
    fill: red;
  }
</style>

生成html <div data-v-9b8ff292="" class="icon"><svg>...</svg></div>

生成css .info svg[data-v-9b8ff292] { fill: red; }

如您所见,v-html 内容没有 data-v 属性,但生成 css 具有 svg 的 data-v 属性。

我知道这是 vue-loader (https://github.com/vuejs/vue-loader/issues/359) 的预期行为。并在本期中提到了后代选择器。但是正如您所看到的,我在我的 css 中使用了它,但没有用。

如何设置 v-html 内容的样式?

vue-loader 的新版本(从版本 12.2.0 开始)允许您使用 "deep scoped" css。你需要这样使用它:

<style scoped> now support "deep" selectors that can affect child components using the >>> combinator:

.foo >>> .bar { color: red; } will be compiled into:

.foo[data-v-xxxxxxx] .bar { color: red; }

有关 the release page 的更多信息 vue-loader

AS Sarumatee 说如果接受的答案不起作用试试:

.foo /deep/ .bar { color: red; }

我正在使用 vue-loader 15.9.1>>> 解决方案对我不起作用(无效),而 /deep/ 方法导致构建错误...

以下是有效的方法:

.foo ::v-deep .bar { color: red; }

在 SCSS 中使用 /deep/ 选择器对我不起作用,但后来我尝试使用 ::v-deep 选择器

例如

::v-deep a {
  color: red;
}

查看答案