about
本篇演示vue3+vite4+echarts+Djangorestframework下的echarts图表应用。
bash
# 想要在vue3中使用echarts,需要先下载
npm install echarts --save
# 示例中用到了axios,也要下载下
npm install axios --save
Django+vue3示例
django3.2+djangorestframework3.14.0 + vue3
后端代码
python
"""
总路由urls.py
"""
from django.views.static import serve
from django.urls import path, include, re_path
from django.conf import settings
urlpatterns = [
path('api/', include(('api.urls', 'api'), namespace='api')),
re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}, name='media')
]
"""
子路由urls.py
"""
from django.urls import path, re_path
from rest_framework import routers
from api.views import account, basic, wallet, address, orders_views
router = routers.SimpleRouter()
router.register(r'basic/info', basic.BasicInfoView)
router.register(r'auth', account.AuthView)
urlpatterns = [
path('charts/', account.myCharts.as_view()),
]
urlpatterns += router.urls
python
"""
视图文件account.py
"""
import random
from rest_framework.views import APIView
from rest_framework.response import Response
class myCharts(APIView):
def get(self, request):
# 我这里只是简单用随机模块生成一些模拟数据,其实这里你可以查MySQL,查redis,只要能把数据处理成前端图表需要的格式即可
simple_data = random.sample(range(100, 1000), 7)
smooth_data = random.sample(range(100, 1000), 7)
bar_simple = random.sample(range(100, 1000), 7)
return Response({"code": 0, "data": {
"simple_data": simple_data,
"smooth_data": smooth_data,
"bar_simple": bar_simple,
}})
前端代码
json
/*
版本依赖情况,package.json
*/
{
"name": "vue3_vite",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"axios": "^1.5.1",
"echarts": "^5.4.3",
"vue": "^3.3.4"
},
"devDependencies": {
"@vitejs/plugin-vue": "^4.2.3",
"vite": "^4.4.5"
}
}
javascript
/*
src/utils/axios.js
*/
import axios from 'axios'
// $开头以示区分,你随便命名都行
const $axios = axios.create({
baseURL: "http://127.0.0.1:8200",
timeout: 2000
})
export default $axios
javascript
/*
src/main.js中,你也可以将axios对象挂载到vue对象上,从而全局引用,但我这里没有这么做,而是在需要的页面中直接引入axios了,毕竟是简单示例,没必要搞那么复杂
*/
import { createApp } from 'vue'
// import './style.css'
import App from './App.vue'
// // 就这一行
// import $axios from "./utils/axios";
const app = createApp(App)
// 添加到vue对象上,可以在全局通过 this.$axios来调用
// app.config.globalProperties.$axios = $axios;
app.mount('#app')
vue
/*
渲染echarts就可以在具体的文件中了
各种echarts图表可以参考:https://echarts.apache.org/examples/zh/index.html
想要看图表的各种参数配置,参考:https://echarts.apache.org/zh/option.html#title
*/
<template>
<div class="container">
<div id="lineSimple" style="height: 600px;width: 800px;"></div>
<div id="lineSmooth" style="height: 600px;width: 800px;"></div>
<div id="areaBasic" style="height: 600px;width: 800px;"></div>
<div id="barSimple" style="height: 600px;width: 800px;"></div>
<div ref="echartsRef" style="height: 600px;width: 800px;"></div>
</div>
</template>
<script setup>
import {onMounted, ref} from "vue";
// 哪个页面用,就先导入echarts
import * as echarts from 'echarts'
import $axios from "../utils/axios";
// 基础折线图示例
function lineSimple(lineSimpleChart) {
$axios.get('/api/charts/').then((res)=>{
lineSimpleChart.setOption( {
title:{
show: true,
text:"基础折线图示例,每两秒向后端请求最新数据并更新数据"
},
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: res.data.data.simple_data, // 折线图需要的动态数据从后端获取即可
type: 'line'
}
]
})
}).catch((error)=>{})
}
// 基础平滑折线图示例
function lineSmooth(lineSimpleChart) {
$axios.get('/api/charts/').then((res)=>{
lineSimpleChart.setOption({
title:{
show: true,
text:"基础平滑折线图示例,每两秒向后端请求最新数据并更新数据"
},
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: res.data.data.smooth_data, // 折线图需要的动态数据从后端获取即可
type: 'line',
smooth: true
}
]
})
}).catch((error)=>{})
}
// 基础面积图示例
function areaBasic(areaBasicChart) {
areaBasicChart.setOption({
title:{
show: true,
text:"基础面积图示例,静态展示数据,无后端交互"
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'line',
areaStyle: {}
}
]
})
}
// 基础柱状图示例
function barSimple(barSimpleChart) {
$axios.get('/api/charts/').then((res)=>{
barSimpleChart.setOption({
title:{
show: true,
text:"基础柱状图示例,只向后端获取一次数据"
},
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: res.data.data.bar_simple, // 需要的动态数据从后端获取即可
type: 'bar'
}
]
})
}).catch((error)=>{})
}
onMounted(() => {
/*
* 图表的基本用法,告诉你vue3中就这么引用的echarts
* */
// 1. 等dom加载完毕,我们获取到对应的div标签,然后进行echarts.init初始化对象
let areaBasicChart = echarts.init(document.getElementById('areaBasic'));
// 2. 为了能比较灵活的根据数据重复渲染图表,我这里将渲染图表部分封装成了函数
areaBasic(areaBasicChart)
/*
* 页面加载完毕,只向后台获取一次数据,然后渲染图表,后续不在动态更新
* */
let barSimpleChart = echarts.init(document.getElementById('barSimple'));
barSimple(barSimpleChart)
/*
* 页面加载完毕,轮训向后台获取最新数据,然后动态的在页面进行渲染
* */
// 注意,当dom加载完毕后,我们才能展开echarts的工作,所以要放在onMounted中处理
// 而且,每个图表的echarts.init只需要初始化一次即可,后续轮训只需根据动态的数据即可让图表动态渲染起来
let lineSmoothChart = echarts.init(document.getElementById('lineSmooth'));
let lineSimpleChart = echarts.init(document.getElementById('lineSimple'));
// 页面渲染完毕先展示下图表,否则页面渲染完毕要等两秒才动态展示,不太美观
lineSimple(lineSimpleChart)
lineSmooth(lineSmoothChart)
// 每两秒像后端请求一次最新的数据
setInterval(()=>{
lineSimple(lineSimpleChart)
lineSmooth(lineSmoothChart)
}, 4000)
})
/*
******************** 以上为第一种方案,下面是第二种方案********************
* */
const echartsRef = ref('');
onMounted(()=>{
const chart = echarts.init(echartsRef.value);
$axios.get('/api/charts/').then((res)=>{
chart.setOption({
title:{
show: true,
text:"echarts示例的另一种写法实现"
},
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: res.data.data.bar_simple, // 需要的动态数据从后端获取即可
type: 'bar'
}
]
})
}).catch((error)=>{})
})
</script>
<style scoped>
.container{
display: flex;
flex-direction: row;
justify-content: space-between;
width: 90%;
}
</style>
实现效果:
g)