Jeremy Thomas
Jeremy Thomas

Reputation: 6684

Vue using input to modify chart

I have a Vue component where I am confusing where to use data vs. prop vs. computed property.

Purpose: I would like to have an input that changes the maximum on my chart.

Vue.component('chartist', {
  template: "#chartist",
  props: {
    value: Object,
    show_controls: {
      type: Boolean,
      default: false
    },
    min: Number,
    max: Number
  },
  data: function() {
    return {
      data: [],
      calcMax: null,
      calcMin: null,
      chart: null
    }
  },
  methods: {
    createData(d) {
      let data = Object.assign({}, d)

      let referrers = Object.keys(data)
      let vals = Object.values(data)

      let final_data = []

      for ( let ref of referrers ) {
        let temp = {}
        temp['name'] = ref
        temp['data'] = data[ref]
        final_data.push(temp)
      }

      this.data = final_data
    }
  },
  computed: {
    otherMax: () => {
      this.chart.options['max'] = this.calcMax
    }
  },
  mounted() {
    this.createData(this.value)
    this.chart = new Chartkick.LineChart(this.$refs.timechart, this.data)
  } 
})

My chart gets initialized in the mounted() hook, and when I update calcMax I'd like to assign that value to the chart's options i.e.

this.chart.options['max'] = this.calcMax

HTML

<script type="text/x-template" id="chartist">
    <div class="card">
        <div class="card-header card-chart" style="min-height:300px;" data-background-color="orange">
            <div id="timechart" style="min-height:300px;" ref='timechart' v-bind:class="'chart' + location.id"></div>
        </div>
        <div class="card-content">
            <div v-if="show_controls">
                <input type="number" v-model="calcMax">
                <input type="number" v-model="calcMin">
            </div>
        </div>
    </div>
</script>

What is the correct pattern to accomplish this?

Upvotes: 1

Views: 152

Answers (1)

Brandon Deo
Brandon Deo

Reputation: 4305

Just watch the value for calcMax and perform the update when it changes.

watch: {
  calcMax(v) {
    this.chart.options.max = v;
  }
}

More on Vue's watchers: Watchers

Upvotes: 1

Related Questions