【问题标题】:have different bar colors in vuetify sparkline在 vuetify 迷你图中有不同的条形颜色
【发布时间】:2020-11-10 16:11:20
【问题描述】:

我在我的 vue/vuetify 项目中有这个迷你图组件,我想根据我所拥有的栏所包含的值来更改栏:

我想把小于0的条的颜色改成红色

这是我的代码的简化版本:

 <v-sparkline
     :gradient="['#5EF7B7','#0CBB72']"
     type="bar"
     show-labels
     auto-line-width
     :value="value"
  ></v-sparkline>

保存值的数据:

value: [0, 2, 5, 9, 5, 10, 3, 5, -4, -10, 1, 8, 2, 9, 0]

我的问题是,有没有办法为不同的值设置不同的条形颜色?

【问题讨论】:

  • 我认为没有办法。迷你图适用于单个数据集

标签: vue.js charts vuetify.js nuxt.js


【解决方案1】:

由于VSparkline 不只是直接绘制条形和填充渐变,而是使用clipPath 来查看后面的渐变,所以我认为没有简单的方法可以做到这一点。

幸运的是,Vuetify 允许我们轻松扩展它们的组件。所以我们可以扩展VSparkline 来满足您的要求。

示例代码:

import { VSparkline } from "vuetify/lib";
import { genBars } from "vuetify/src/components/VSparkline/helpers/core";

export default {
  extends: VSparkline,
  props: {
    barColors: {
      type: Array
    }
  },
  methods: {
    genBars() {
      if (!this.value || this.totalValues < 2) return;

      let bars = genBars(this.normalizedValues, this.boundary);
      let offsetX = (Math.abs(bars[0].x - bars[1].x) - this._lineWidth) / 2;
      let width = this._lineWidth;

      bars = bars.map((bar, index) => ({
        ...bar,
        fill: this.barColors[index]
      }));

      return this.$createElement(
        "svg",
        {
          attrs: {
            display: "block",
            viewBox: `0 0 ${this.totalWidth} ${this.totalHeight}`
          }
        },
        [
          ...bars.map(item =>
            this.$createElement("rect", {
              attrs: {
                x: item.x + offsetX,
                y: item.y,
                width,
                height: item.height,
                fill: item.fill
              }
            })
          ),
          this.hasLabels ? this.genLabels(offsetX) : undefined
        ]
      );
    }
  }
};

在此示例中,我删除了一些不必要的代码,以便更容易演示,但您可能需要在实际项目中使用。见VSparkline.ts

CodeSandbox

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    相关资源
    最近更新 更多