问题
I am trying to use reactive data mixin for vue-chartjs
The mounted function to set the initial data is working and I can see the chart correctly using the API response:
fetchSessionTrends() {
axios.get(endpoint)
.then(({data}) => {
this.sessions = data.map(session => session.sessions);
this.sessionLabels = data.map(label => label.date);
this.loaded = true;
});
},
The data:
data() {
return {
endpoint: 'public/api/sessions',
sessions: [],
sessionLabels: [],
loaded: false,
daysFilter: 14
};
},
I am display the chart with a text field to provide the reactive portion - expectation is that it calls the endpoint again and receives new response
<div class="col-md-2 session-filter">
<div class="input-group">
<input type="text" class="form-control" placeholder="days..." v-model="daysFilter">
<span class="input-group-btn">
<button class="btn btn-secondary" type="button" @click="refreshSessions">Go</button>
</span>
</div>
</div>
<line-chart v-if="loaded" :chart-data="sessions" :chart-labels="sessionLabels"></line-chart>
To test the reactive part however, for now I am simply changing the data arrays directly to see how it works:
refreshSessions() {
this.sessions = [1, 2, 3];
this.sessionlabels = ["june", "july", "august"];
},
Right, so this is giving me the errors
[Vue warn]: Error in callback for watcher "chartData": "TypeError: Cannot read property 'map' of undefined" found in ....
TypeError: Cannot read property 'map' of undefined
LineChart.js is as described in the docs, abbreviated here for space
import { Line, mixins } from 'vue-chartjs';
const { reactiveProp } = mixins
extends: Line,
mixins: [reactiveProp],
props: {
chartData: {
type: Array,
required: true
},
chartLabels: {
type: Array,
required: true
}
},
mounted() {
this.renderChart({
labels: this.chartLabels,
datasets: [
{
label: 'sessions',
data: this.chartData
}
]
}, this.options)
}
So, chart is initially working fine but I can't seem to get the reactive part working.
回答1:
This will not work. Because the reactiveMixins assume that chartData
is the whole chartjs dataset object. With the dataset array, with the labels etc.
But you are splitting it up, this way the reactiveMixins can't work. Because your chartData is only the pure data of one dataset.
To solve it, you can do two things:
- Pass in the whole dataset object
- Add own watchers.
I guess the most simple method would be to add two watchers to watch chartData
and chartLabel
and on a change call this.$data._chart.update()
来源:https://stackoverflow.com/questions/47278617/vue-chartjs-reactive-data-error