Vue.js + Chartist:在组件中使用图表
Vue.js + Chartist: Using charts in a component
我有一个组件可以访问生成 Chartist 图表所需的数据,但我不确定如何生成图表。这是我的组件:
Vue.component('chart-card', {
template: "#chart-card",
props: {
location: Object,
appointments: Object
},
data: function() {
return {
data: {}
}
},
computed: {
fetchAppointments: function() {
var that = this;
$.ajax({
method: 'GET',
data: { location_id: this.location.id },
url: `/appointments.json`,
success: function(res) {
that.data = {
labels: Object.keys(res),
seried: Object.values(res)
}
}
})
}
}
})
和 data
变成这样:
data: {
labels: [
"Consultation",
"Weekly Sessions",
"Re-Eval Week",
"Full Maintenance",
"Limited Maintenance",
"Re-Starting the Program"
],
series: [4, 24, 3, 1, 4, 1]
}
当我尝试生成需要 DOM 元素的图表时,我 运行 陷入了这个问题:
new Chartist.Pie(DOM_ELEMENT_HERE, data, options )
我应该在 Vue 组件中的什么地方进行调用?
您的数据提取不属于计算 属性,它应该是一个方法调用,因为它是异步的。在您的情况下,fetchAppointments
的值将始终为 undefined
。
您可以在 mounted
lifecycle hook and refer to the appropriate DOM node using the $el
property 中构建图表。
我对您尝试执行的操作的版本如下所示:
Vue.component({
template: "#chart-card",
props: {
location: Object,
appointments: Object
},
methods: {
fetchAppointments() {
return new Promise((resolve, reject) => {
$.ajax({
method: 'GET',
data: { location_id: this.location.id },
url: `/appointments.json`,
success: res => resolve({
labels: Object.keys(res),
seried: Object.values(res)
})
});
});
}
},
mounted() {
this.fetchAppointments().then(data => {
new Chartist.Pie(this.$el, data, options);
});
}
});
我有一个组件可以访问生成 Chartist 图表所需的数据,但我不确定如何生成图表。这是我的组件:
Vue.component('chart-card', {
template: "#chart-card",
props: {
location: Object,
appointments: Object
},
data: function() {
return {
data: {}
}
},
computed: {
fetchAppointments: function() {
var that = this;
$.ajax({
method: 'GET',
data: { location_id: this.location.id },
url: `/appointments.json`,
success: function(res) {
that.data = {
labels: Object.keys(res),
seried: Object.values(res)
}
}
})
}
}
})
和 data
变成这样:
data: {
labels: [
"Consultation",
"Weekly Sessions",
"Re-Eval Week",
"Full Maintenance",
"Limited Maintenance",
"Re-Starting the Program"
],
series: [4, 24, 3, 1, 4, 1]
}
当我尝试生成需要 DOM 元素的图表时,我 运行 陷入了这个问题:
new Chartist.Pie(DOM_ELEMENT_HERE, data, options )
我应该在 Vue 组件中的什么地方进行调用?
您的数据提取不属于计算 属性,它应该是一个方法调用,因为它是异步的。在您的情况下,fetchAppointments
的值将始终为 undefined
。
您可以在 mounted
lifecycle hook and refer to the appropriate DOM node using the $el
property 中构建图表。
我对您尝试执行的操作的版本如下所示:
Vue.component({
template: "#chart-card",
props: {
location: Object,
appointments: Object
},
methods: {
fetchAppointments() {
return new Promise((resolve, reject) => {
$.ajax({
method: 'GET',
data: { location_id: this.location.id },
url: `/appointments.json`,
success: res => resolve({
labels: Object.keys(res),
seried: Object.values(res)
})
});
});
}
},
mounted() {
this.fetchAppointments().then(data => {
new Chartist.Pie(this.$el, data, options);
});
}
});