Project scenario:
Use Echarts to visualize charts in vue, the official website is as follows
Install and use:
① Obtain from npm
npm install echarts --save
② Introduce ECharts into the vue project
Global import method, in main.js
//全局引入echarts(最新版5.0),在main.js里
import * as echarts from 'echarts'
Vue.prototype.$echarts = echarts
③Create a container in a single page file
//在页面文件里创建一个div,一定要设置高!不然图表出不来!
<div id="chart" style="height: 600px" ref="chart"></div>
Be sure to set the height for the container ! Otherwise the chart will not come out!
④ Define an instance of echarts in vue's data
//在data里定义一个实例,名字跟容器里的ref一致
export default {
data () {
return {
chart: null // echarts图表实例
}
},
Note: It is important to keep the property names defined by ref consistent
⑤Used in the methods layer
// methods层负责定义方法
methods: {
initChart () {
// 初始化echarts
this.chart = this.$echarts.init(this.$refs.chart)
// 设置图表option(配置项)绘制图表
// 绘制图表
this.chart.setOption({
title: {
text: '商品销售数据'
},
tooltip: {},
xAxis: {
data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
},
yAxis: {
type: 'value'
},
backgroundColor: '#dddddd',
color: ['#72ccff', '#d4a4eb'],
series: [
{
name: '销量',
type: 'bar', // 柱状图
data: [5, 20, 36, 10, 10, 20]
},
{
name: '利润',
smooth: true,
type: 'line', // 折线图
data: [2, 23, 5, 54, 9, 33]
}
]
})
},
},
⑥Initialize the page in mounted
//mounted和methods同层级,不要嵌套到methods里,逗号隔开
mounted () {
// 在这里初始化 echarts 因为初始化要传实例
this.initChart()
},
mounted and methods are at the same level, avoid nesting
If you don't understand, look at the vue life cycle.
simple science,
mounted
: dom rendering is complete, component mounting is complete, and the page effect is realizedmethods
: Event method execution, Vue's behavior layer
Rendering effect:
Full code:
<template>
<div id="chart" style="height: 400px" ref="chart"></div>
</template>
<script>
export default {
data() {
chart: null // echarts图表实例
},
methods: {
initChart () {
this.chart = this.$echarts.init(this.$refs.chart)
this.chart.setOption({
title: {
text: '商品销售数据'
},
tooltip: {},
xAxis: {
data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
},
yAxis: {
type: 'value'
},
backgroundColor: '#dddddd',
color: ['#72ccff', '#d4a4eb'],
series: [
{
name: '销量',
type: 'bar', // 柱状图
data: [5, 20, 36, 10, 10, 20]
},
{
name: '利润',
smooth: true,
type: 'line', // 折线图
data: [2, 23, 5, 54, 9, 33]
}
]
})
},
},
mounted () {
this.initChart()
},
</script>
The author's previous article: Solve the problem of front-end projects, export the excel file based on the back-end interface of vue_Yichu's blog-CSDN blog structure layer, behavior layer, data layer, the effect is as follows, https://blog.csdn.net /weixin_43928112/article/details/125187111