Vue单文件组件绑定data-v-xxxxxxxx到生成的元素

2022-01-25 00:00:00 html css vue.js vue-component sass

我正在构建一个 Vue 组件作为单个文件组件:

<模板><div class="chart"></div></模板><脚本>从'd3'导入*作为d3;导出默认{数据() {返回 {数据:[4、8、15、16、23、42],};},挂载(){d3.select('.chart').selectAll('div').data(这个.data).进入().append('div').style('width', d => `${10 * d}px`).text(d => d);},};</脚本><style lang="scss" 作用域>.图表 {分区 {背景颜色:钢蓝;白颜色;字体:10px 无衬线;边距:1px;填充:3px;文本对齐:右;}}</风格>

使用 webpack 处理后,CSS 呈现如下:

<style type="text/css">.chart div[数据-v-xxxxxxxx] {背景颜色:钢蓝;白颜色;字体:10px 无衬线;边距:1px;填充:3px;文本对齐:右;}</风格>

但 HTML 显示为:

我正在使用 D3 生成子 <div>s.我发现 data-v-xxxxxxxx 没有绑定到生成的元素.如果我在原始模板中包含子 <div>s 而不是生成它们,它们每个都有 data-v-xxxxxxxx 属性并且样式按预期应用

我认为根节点的任何后代,无论是包含在模板中还是生成的,都应该绑定到范围 CSS 的规则.有什么办法可以强制吗?

解决方案

新版本的 vue-loader(从版本 12.2.0 开始)允许您使用深度作用域"css.你需要这样使用它:

<块引用>

<style scoped> 现在支持可以影响子级的深度"选择器使用 >>> 组合子的组件:

.foo >>>.bar { 颜色:红色;} 会被编译成:

.foo[data-v-xxxxxxx] .bar { 颜色:红色;}

vue-loader发布页面的更多信息代码>

I'm building a Vue component as a Single File Component:

<template>
  <div class="chart"></div>
</template>

<script>
import * as d3 from 'd3';

export default {
  data() {
    return {
      data: [4, 8, 15, 16, 23, 42],
    };
  },
  mounted() {
    d3.select('.chart')
      .selectAll('div')
        .data(this.data)
      .enter()
        .append('div')
        .style('width', d => `${10 * d}px`)
        .text(d => d);
  },
};
</script>

<style lang="scss" scoped>
.chart {
  div {
    background-color: steelblue;
    color: white;
    font: 10px sans-serif;
    margin: 1px;
    padding: 3px;
    text-align: right;
  }
}
</style>

After processing with webpack, the CSS is rendered like so:

<style type="text/css">
.chart div[data-v-xxxxxxxx] {
  background-color: steelblue;
  color: white;
  font: 10px sans-serif;
  margin: 1px;
  padding: 3px;
  text-align: right;
}
</style>

But the HTML shows up as:

<div data-v-xxxxxxxx class="chart">
    <div style="width: 40px;">4</div>
    <div style="width: 80px;">8</div>
    <div style="width: 150px;">15</div>
    <div style="width: 160px;">16</div>
    <div style="width: 230px;">23</div>
    <div style="width: 420px;">42</div>
</div>

I'm using D3 to generate the child <div>s. I've found that data-v-xxxxxxxx isn't bound to generated elements. If I include the child <div>s in the original template rather than generating them, they each have the data-v-xxxxxxxx attribute and the styles apply as expected

I would think that any descendant of the root node, whether included in the template or generated, should be bound to the rules of the scoped CSS. Is there any way to force this?

解决方案

New version of vue-loader (from version 12.2.0) allows you to use "deep scoped" css. You need to use it that way:

<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; }

More informations on the release page of vue-loader

相关文章