//1、安装脚手架 npm install vue vue-router vue-echarts socket.io-client // 2、创建Chart.vue组件 <template> <div> <div ref="chart" style="height: 300px;"></div> </div> </template> <script> import echarts from 'vue-echarts' import io from 'socket.io-client' export default { components: { 'v-chart': echarts }, data() { return { chartData: [] } }, mounted() { // 创建WebSocket连接 const socket = io('http://localhost:3000') // 监听数据更新事件 socket.on('chartData', data => { this.chartData = data // 渲染图表 this.renderChart() }) }, methods: { // 渲染图表 renderChart() { this.$refs.chart.clear() this.$refs.chart.setOption({ // 图表配置项 title: { text: '实时统计图表' }, xAxis: { type: 'category', data: this.chartData.map(item => item.name) }, yAxis: { type: 'value' }, series: [{ type: 'bar', data: this.chartData.map(item => item.value) }] }) } } } </script> //3、引入统计图表组件 <template> <div> <chart></chart> </div> </template> <script> import Chart from '../components/Chart.vue' export default { components: { Chart } } </script>