question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Reactivity of Options

See original GitHub issue

I need to have Options be reactive so that it will update the title property. It does not appear to be watched in the mixin? No matter what I do below, the title will not re-render on the chart.

// lineChart.js
import { Line, mixins } from 'vue-chartjs'

export default Line.extend({
  mixins: [mixins.reactiveProp],
  props: ['chartData', 'options'],
  mounted () {
    this.renderChart(this.chartData, this.options)
  }
})
// Nevermind the inconsistency that the "bar" component is delivering a "line" :)
// chart component
<template lang="pug">
.columns
  .column.is-11.is-offset-1
    .card
      bar-chart(v-bind:chartData='chartData' 
                v-bind:options='chartOptions' 
                v-bind:height='340', v-bind:width='960' )
</template>

<script>
const moment = require('moment')
const axios = require('axios')
const config = require('../config')
import BarChart from '../components/BarChart.js'

require('moment-duration-format')

export default {
  name: 'flight-trend-chart',
  components: {
    BarChart
  },
  data () {
    return {
      chartData: {},
      cheapFlightsByEndpoint: [],
      chartOptions: {}
    }
  },
  computed: {
    title: function () {
      return 'Flights from ' + this.origin + ' to ' + this.destination
    }
  },
  methods: {
    loadCheapFlightsByEndpoint: function (origin, destination) {
      axios.get(config.api_base_url + '/flights-by-endpoints?origin=' + origin + '&destination=' + destination)
        .then(response => {
          this.cheapFlightsByEndpoint = response.data
          this.chartData = this.makeChartData()
          console.log(this.title)
          this.chartOptions = this.makeChartOption(this.title)
        })
    },
    makeChartOption: function (title) {
      return {
        responsive: false,
        title: {
          display: true,
          text: title,
          fontSize: 16
        },
        scales: {
          yAxes: [{
            gridLines: {
              display: true,
              color: 'rgba(0,0,0,0.1)'
            },
            ticks: {
              beginAtZero: false
            }
          }]
        }
      }
    },
    makeChartData: function () {
      let dates = this.cheapFlightsByEndpoint.map(function (a) { return moment(a.created).format('MM/DD/YYYY') })
      let lowPrices = this.cheapFlightsByEndpoint.map(function (a) { return a.low_price })
      let avgPrices = this.cheapFlightsByEndpoint.map(function (a) { return a.avg_price })
      let data = {
        labels: dates,
        datasets: [
          {
            label: 'Low Prices',
            borderWidth: 1,
            pointRadius: 2,
            data: lowPrices,
            backgroundColor: 'rgba(0, 14, 14, 0.57)'
          },
          {
            label: 'Avg Prices',
            borderWidth: 1,
            pointRadius: 2,
            data: avgPrices,
            backgroundColor: 'rgba(4, 112, 110, 0.57)'
          }
        ]
      }
      return data
    }
  },
  props: {
    origin: {type: String, required: true},
    destination: {type: String, required: true}
  },
  created: function () {
    this.loadCheapFlightsByEndpoint(this.origin, this.destination)
  },
  watch: {
    origin: function () {
      this.loadCheapFlightsByEndpoint(this.origin, this.destination)
    },
    destination: function () {
      this.loadCheapFlightsByEndpoint(this.origin, this.destination)
    }
  }
}
</script>

Environment

  • vue.js version: 2.1.10
  • vue-chart.js version: 2.5.6
  • npm version: 3.10.3

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:3
  • Comments:10 (5 by maintainers)

github_iconTop GitHub Comments

15reactions
aperturelesscommented, May 8, 2017

Hi @crholliday Yeah the options are not reactive by default. But like @euledge pointed out, you can simply add a watcher by yourself.

You could try to call this._chart.update() which is the internal chart.js method to update the chart instance. However I am not sure if this will work with options.

If this is not working, calling renderChart() is the right way. But you should destroy the old instance before you do so. Because renderChart() creates a new chartjs instance. Which could lead to weird problems.

import { Line, mixins } from 'vue-chartjs'

export default Line.extend({
  mixins: [mixins.reactiveProp],
  props: ['chartData', 'options'],
  watch: {
    'options': {
      handler (newOption, oldOption) {
        this._chart.destroy()
        this.renderChart(this.chartData, this.options)
      },
      deep: true
    }
  },
  mounted () {
    this.renderChart(this.chartData, this.options)
  }
})

I will see if I can implement it as a feature ✌️ so it will work out of the box

8reactions
euledgecommented, May 8, 2017

I feel the same thing as you. Now I implement with the following way. I hope it will be possible to watch options as mixins.reactiveProp too.

export default Line.extend({
  mixins: [mixins.reactiveProp],
  props: ['chartData', 'options'],
  watch: {
    'options': {
      handler(newOption, oldOption) {
        this.renderChart(this.chartData, this.options)
      },
      deep: true
    }
  }
});
Read more comments on GitHub >

github_iconTop Results From Across the Web

The Anatomy of Options - Investopedia
Rho appraises the reactivity of the option value to the interest rate: it is the measure of the option value with respect to...
Read more >
Reactivity API: Core - Vue.js
Details. The ref object is mutable - i.e. you can assign new values to .value . It is also reactive - i.e. any...
Read more >
Reactivity of carboxylic acid derivatives (video) - Khan Academy
Reactivity and stability are two opposing concepts. The more stable a molecule is, the less it wants to react. A decrease in stability...
Read more >
Reaction Search - the NIST WebBook
This option excludes reactions which involve ions as reactants or products. Reaction type help (step 3) (Back to search). Searches may be restricted...
Read more >
Reactivity control options of space nuclear reactors
This paper compares two ex-core control options of the gas-cooled Submersion Subcritical Safe Space (S^4) reactor with a fast neutrons energy spectrum: (a) ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found