Vue使用 Echarts
1.安装 echarts 插件
npm install echarts -save
2.在main.js 引入 echarts
import Vue from 'vue'
import App from './App'
import router from './router'
import echarts from 'echarts'
Vue.config.productionTip = false
Vue.prototype.$echarts = echarts; //将 echarts 插件 对象 赋值到 vue 实例的 原型上,这样 所有的 vue实例都可以 直接 this.$ecgarts.xxx 调用 echarts 的方法
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
3.使用
在某个 组件 methods:{…} 内定义一个 方法 用于 初始化 图表
该组件模板:
<template>
<div>
...
<div id="id"></div>
...
</div>
</template>
...
methods:{
createEchars(){
let myEcharts = this.$echarts.init(document.getElementById(id)); //初始化 echarts 将图标绑定到指定的 DOM 节点上
myEcharts.setOption(this.options); // 设置 图表 属性 数据
}
}
然后在该组件的 mounted 生命周期 函数 内 执行 这个 方法
mounted(){
this.createEchars();// 组件生成 就执行 初始化 图表
}
4.将图表功能 简单 封装成 组件
<template>
<div>
<div :id="id"></div>
</div>
</template>
<script>
export default {
name: "echartsData",
data(){
return {
}
},
mounted(){
this.createEchars();// 组件生成 就执行 初始化 图表
},
methods:{
createEchars(){
let myEcharts = this.$echarts.init(document.getElementById(this.id)); //初始化 echarts 将图标绑定到指定的 DOM 节点上
myEcharts.setOption(this.options);
}
},
props:{
id:{ //用于 标识 echarts 图标 id
type:String,
required: true
},
options:{ // 用于 配置 echarts 图表的 属性 数据
type:Object,
required:true
}
}
}
</script>
该组件的 图表 id options属性 均由 使用 该组件的 组件(父组件) 传入,宽高(样式)也由 传入的 id 在 父组件内 设置
5.使用案例
<template>
<div>
<h2>{{message}}</h2>
<echarts-data :id="'my-echarts'" :options="options"></echarts-data>
</div>
</template>
<script>
import echartsData from './echartsData'
export default {
name:'Test',
data(){
return {
message:'这是测试页面',
options:''
}
},
//此处 只能是 created 或者 beforeMount 必须是在 data 属性初始化完成,但 DOM 却未渲染 时期 进行 处理
beforeMount(){ //此处 不能修改为 mounted 因为 mounted 方法 为 DOM 节点渲染 完后执行,此时作为 子组件的 echarts-data 已经完成了渲染,所以接受的options值为 '',最终会导致报错(因为echarts-data 组件中设置了 option属性必须为Object)
this.options = {
title: {
text: '折线图堆叠'
},
tooltip: {
trigger: 'axis'
},
legend: {
data:['邮件营销','联盟广告','视频广告','直接访问','搜索引擎']
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
toolbox: {
feature: {
saveAsImage: {}
}
},
xAxis: {
type: 'category',
boundaryGap: false,
data: ['周一','周二','周三','周四','周五','周六','周日']
},
yAxis: {
type: 'value'
},
series: [
{
name:'邮件营销',
type:'line',
stack: '总量',
data:[120, 132, 101, 134, 90, 230, 210]
},
{
name:'联盟广告',
type:'line',
stack: '总量',
data:[220, 182, 191, 234, 290, 330, 310]
},
{
name:'视频广告',
type:'line',
stack: '总量',
data:[150, 232, 201, 154, 190, 330, 410]
},
{
name:'直接访问',
type:'line',
stack: '总量',
data:[320, 332, 301, 334, 390, 330, 320]
},
{
name:'搜索引擎',
type:'line',
stack: '总量',
data:[820, 932, 901, 934, 1290, 1330, 1320]
}
]
}
},
components:{
'echarts-data':echartsData
}
}
</script>
<style>
#my-echarts{
width:750px;
height:500px;
border:1px solid #f40;
}
</style>