主题
使用 Axios
Chart.js 的数据可以通过多种方式异步获取。Axios 是一个基于 Promise 的 HTTP 客户端,使用简洁,支持拦截器和请求取消等功能,适合复杂场景。
下面示例展示如何用 Axios 请求数据,并更新折线图的数据内容。
js
const ctx = document.getElementById("axiosChart").getContext("2d");
const axiosChart = new Chart(ctx, {
type: "bar",
data: {
labels: [],
datasets: [
{
label: "访问量",
data: [],
backgroundColor: "rgba(255, 159, 64, 0.7)",
},
],
},
options: {
responsive: true,
plugins: {
legend: { display: true },
},
},
});
// 使用 Axios 获取数据
axios
.get("https://jsonplaceholder.typicode.com/comments?_limit=5")
.then((response) => {
const data = response.data;
axiosChart.data.labels = data.map((item) => "评论ID " + item.id);
axiosChart.data.datasets[0].data = data.map((item) => item.body.length);
axiosChart.update();
})
.catch((error) => {
console.error("Axios 请求失败", error);
});示例无法以 iframe 加载(请检查路径或将 demo 放到 public/)。