以前在使用echarts的时候,想要根据选择条件让echarts的图片也跟着变化,我经常是放在vue的watch中监听数据的变化来实现的。但是这里我发现了一个更加简单的方法,不需要在vue的watch中监听数据也可以实现,具体代码和运行结果如下所示
echarts官网示例
Examples - Apache ECharts
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js">script>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://unpkg.com/element-ui/lib/index.js">script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.4.1/echarts.min.js">script>
head>
<body>
<div id="app">
<div id="main" style="width: 500px; height: 400px;">div>
div>
<script>
var app = new Vue({
el: '#app',
data: {
myChart: null
},
methods: {
// 初始化echarts
initEcharts() {
var chartDom = document.getElementById('main');
// 将创建的echarts示例放到vue的data中,这样在这个界面就想到于全局配置了
this.myChart = echarts.init(chartDom);
},
// 配置echarts的option,展示数据图表
setEchartsOption() {
// 这里可以发送axios请求,然后通过响应的数据赋值给对应的x轴和y轴即可,由于这里没有于后端联调,所以简单请求判断一下,
// 请求后端大概也是这个过程
var option;
option = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: [
{
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
axisTick: {
alignWithLabel: true
}
}
],
yAxis: [
{
type: 'value'
}
],
series: [
{
name: 'Direct',
type: 'bar',
barWidth: '60%',
data: [10, 52, 200, 334, 390, 330, 220]
}
]
};
option && this.myChart.setOption(option);
},
},
mounted() {
// 注意调用顺序,先初始化echarts才给echarts赋值
this.initEcharts()
this.setEchartsOption()
}
})
script>
body>
html>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js">script>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://unpkg.com/element-ui/lib/index.js">script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.4.1/echarts.min.js">script>
head>
<body>
<div id="app">
<el-row>
<el-select v-model="value" filterable placeholder="请选择" @change="setEchartsOption">
<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
el-option>
el-select>
<el-button type="primary" @click="searchButton">查询el-button>
el-row>
<el-row>
<div id="main" style="width: 500px; height: 400px;">div>
el-row>
div>
<script>
var app = new Vue({
el: '#app',
data: {
myChart: null,
options: [{
value: '星期六',
label: '星期六'
}, {
value: '星期日',
label: '星期日'
}],
value: '星期六',
zhouliu: {
xValue: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
yValue: [10, 52, 200, 334, 390, 330, 220]
},
zhouri: {
xValue: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
yValue: [50, 80, 40, 99, 300, 88, 160]
}
},
methods: {
// 初始化echarts
initEcharts() {
var chartDom = document.getElementById('main');
// 将创建的echarts示例放到vue的data中,这样在这个界面就想到于全局配置了
this.myChart = echarts.init(chartDom);
},
// 配置echarts的option,展示数据图表
setEchartsOption() {
// 这里可以发送axios请求,然后通过响应的数据赋值给对应的x轴和y轴即可,由于这里没有于后端联调,所以简单请求判断一下,
// 请求后端大概也是这个过程
var xValue = null;
var yValue = null;
if (this.value === '星期六') {
xValue = this.zhouliu.xValue
yValue = this.zhouliu.yValue
} else if (this.value === '星期日') {
xValue = this.zhouri.xValue
yValue = this.zhouri.yValue
}
var option;
option = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: [
{
type: 'category',
data: xValue,
axisTick: {
alignWithLabel: true
}
}
],
yAxis: [
{
type: 'value'
}
],
series: [
{
name: 'Direct',
type: 'bar',
barWidth: '60%',
data: yValue
}
]
};
option && this.myChart.setOption(option);
},
searchButton() {
// 为了避免重复初始化echarts, 我们在点击按钮的时候可以调用echarts的clear方法清楚一下,然后再重新调用函数进行对echarts的赋值
this.myChart.clear() // 这一句有没有都可以
this.setEchartsOption()
}
},
mounted() {
// 注意调用顺序,先初始化echarts才给echarts赋值
this.initEcharts()
this.setEchartsOption()
}
})
script>
body>
html>
可以根据传入的时间获得需要的数据
{
"code": 200,
"message": "查询成功!",
"data": [
{
"id": 1,
"count": 24,
"createTime": "2023-02-15T14:17:50"
},
{
"id": 2,
"count": 32,
"createTime": "2023-02-16T14:18:19"
},
{
"id": 3,
"count": 40,
"createTime": "2023-02-17T14:18:30"
},
{
"id": 4,
"count": 16,
"createTime": "2023-02-18T14:18:44"
},
{
"id": 5,
"count": 88,
"createTime": "2023-02-19T14:18:59"
},
{
"id": 6,
"count": 8,
"createTime": "2023-02-20T14:19:11"
},
{
"id": 7,
"count": 160,
"createTime": "2023-02-21T14:19:27"
},
{
"id": 8,
"count": 108,
"createTime": "2023-02-22T14:19:38"
}
]
}
vue+elementUI
可以直接复制使用
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js">script>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://unpkg.com/element-ui/lib/index.js">script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.4.1/echarts.min.js">script>
<script src="https://unpkg.com/axios/dist/axios.min.js">script>
head>
<body>
<div id="app">
<el-row>
<el-date-picker v-model="value1" type="datetimerange" start-placeholder="开始日期" end-placeholder="结束日期"
value-format="yyyy-MM-dd HH:mm:ss" :default-time="['00:00:00']">
el-date-picker>
<el-button type="primary" @click="searchButton">查询el-button>
el-row>
<el-row>
<div id="main" style="width: 500px; height: 400px;">div>
el-row>
div>
<script>
var app = new Vue({
el: '#app',
data: {
myChart: null,
value1: [
'2023-02-15 14:17:50',
'2023-02-22 14:19:38'
],
},
methods: {
// 初始化echarts
initEcharts() {
var chartDom = document.getElementById('main');
// 将创建的echarts示例放到vue的data中,这样在这个界面就想到于全局配置了
this.myChart = echarts.init(chartDom);
},
// 配置echarts的option,展示数据图表
async setEchartsOption() {
// 这里可以发送axios请求,然后通过响应的数据赋值给对应的x轴和y轴即可,由于这里没有于后端联调,所以简单请求判断一下,
const result = await axios.get(`http://localhost:8080/echarts/getechartslistbytime?startTime=${this.value1[0]}&endTime=${this.value1[1]}`)
console.log(result.data.data)
var xValue = null;
var yValue = null;
if (result.data.data) {
xValue = result.data.data.map(item => {
return item.createTime.split('T')[0]
})
yValue = result.data.data.map(item => {
return item.count
})
}
var option;
option = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: [
{
type: 'category',
data: xValue,
axisTick: {
alignWithLabel: true
}
}
],
yAxis: [
{
type: 'value'
}
],
series: [
{
name: '数量',
type: 'bar',
barWidth: '60%',
data: yValue
}
]
};
option && this.myChart.setOption(option);
},
searchButton() {
// 为了避免重复初始化echarts, 我们在点击按钮的时候可以调用echarts的clear方法清楚一下,然后再重新调用函数进行对echarts的赋值
this.myChart.clear() // 这一句有没有都可以
this.setEchartsOption()
}
},
mounted() {
// 注意调用顺序,先初始化echarts才给echarts赋值
this.initEcharts()
this.setEchartsOption()
}
})
script>
body>
html>
其实这里也可以用折线图,过程都差不多的
springboot+mysql+mybatis-plus,刚好这里有springboot结合mybatis-plus的用法
后端代码各个文件的位置截图如下
mysql数据库建表语句和插入数据语句
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for echarts
-- ----------------------------
DROP TABLE IF EXISTS `echarts`;
CREATE TABLE `echarts` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '主键id',
`count` int NULL DEFAULT NULL COMMENT '统计数量',
`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of echarts
-- ----------------------------
INSERT INTO `echarts` VALUES (1, 24, '2023-02-15 14:17:50');
INSERT INTO `echarts` VALUES (2, 32, '2023-02-16 14:18:19');
INSERT INTO `echarts` VALUES (3, 40, '2023-02-17 14:18:30');
INSERT INTO `echarts` VALUES (4, 16, '2023-02-18 14:18:44');
INSERT INTO `echarts` VALUES (5, 88, '2023-02-19 14:18:59');
INSERT INTO `echarts` VALUES (6, 8, '2023-02-20 14:19:11');
INSERT INTO `echarts` VALUES (7, 160, '2023-02-21 14:19:27');
INSERT INTO `echarts` VALUES (8, 108, '2023-02-22 14:19:38');
SET FOREIGN_KEY_CHECKS = 1;
application.yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/echarts-demo?characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root
password: root
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
启动器类
@SpringBootApplication
@MapperScan("com.example.dao")
public class EchartsDemoApplication {
public static void main(String[] args) {
SpringApplication.run(EchartsDemoApplication.class, args);
}
}
Controller
@RestController
@RequestMapping("echarts")
@CrossOrigin // 允许跨域
public class EchartsController{
/**
* 服务对象
*/
@Autowired
private EchartsService echartsService;
@GetMapping("/getechartslistbytime")
public R getEchartsListByTime(String startTime, String endTime) {
return echartsService.getEchartsListByTime(startTime,endTime);
}
}
dao或者mapper
public interface EchartsDao extends BaseMapper<Echarts> {
}
实体类,这里包括统一响应格式的R对象
Echarts类
public class Echarts {
//主键id
private Integer id;
//统计数量
private Integer count;
//创建时间
private LocalDateTime createTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
}
R对象
package com.example.domain;
public class R {
private Integer code;
private String message;
private Object data;
public R(Integer code, String message) {
this.code = code;
this.message = message;
}
public R(Integer code, String message, Object data) {
this.code = code;
this.message = message;
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
Service接口
public interface EchartsService extends IService<Echarts> {
R getEchartsListByTime(String startTime, String endTime);
}
ServiceImpl实现类
@Service("echartsService")
public class EchartsServiceImpl extends ServiceImpl<EchartsDao, Echarts> implements EchartsService {
@Override
public R getEchartsListByTime(String startTime, String endTime) {
LambdaQueryWrapper<Echarts> queryWrapper = new LambdaQueryWrapper<>();
// ge 是>=
queryWrapper.ge((startTime != null && startTime.length() > 0), Echarts::getCreateTime, startTime);
queryWrapper.le((endTime != null && endTime.length() > 0), Echarts::getCreateTime, endTime);
// 这里就相当于SELECT id,count,create_time FROM echarts WHERE (create_time >= ? AND create_time <= ?)
List<Echarts> list = this.list(queryWrapper);
return new R(200, "查询成功!", list);
}
}