//1、Vue前端代码 <template> <div> <canvas id="chart"></canvas> </div> </template> <script> import axios from 'axios'; export default { mounted() { axios.get('http://localhost/api/read.php') .then((response) => { this.createChart(response.data); }) .catch((error) => { console.log(error); }); }, methods: { createChart(data) { const labels = data.map(item => item.month); const values = data.map(item => item.total_amount); new Chart('chart', { type: 'bar', data: { labels, datasets: [{ label: '阅读量', data: values, backgroundColor: 'rgba(75, 192, 192, 0.2)', borderColor: 'rgba(75, 192, 192, 1)', borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } } }); } } } </script> //2、PHP链接数据库代码 // 连接到数据库 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 获取销售记录 $sql = "SELECT SUM(amount) AS total_amount, MONTH(date) AS month FROM sales GROUP BY MONTH(date)"; $result = $conn->query($sql); // 处理查询结果 $data = []; if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $data[] = $row; } } // 返回JSON格式的数据 echo json_encode($data);
注意:在页面中引入https://cdn.jsdelivr.net/npm/chart.js
。