vue 引入 echarts,init初始化报错
1.下载echarts
npm install echarts --save
2.页面中引入,我只有一个页面需要引用到echarts,所以就直接在页面中引入
import echarts from 'echarts'
3.在methods中写对应的例子
myEcharts() {
this.chart = echarts.init(document.getElementById('main'))
this.chart.setOption({
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b} : {c} ({d}%)'
},
legend: {
bottom: 10,
left: 'center',
data: ['已出租', '未出租', '已预约']
},
series: [
{
name: '车辆出租状态',
type: 'pie',
radius: '55%',
center: ['50%', '40%'],
data: [
{ value: 40, name: '已出租' },
{ value: 30, name: '未出租' },
{ value: 30, name: '已预约' }
],
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
})
}
4.在mounted中引用方法
mounted() {
this.myEcharts()
}
结果报错,报init初始化错误
找了半小时,才找到原因,是import方式不对
需要将原先的import echarts from 'echarts'
改成import * as echarts from 'echarts'
。官网中更新的写法。改完之后刷新页面就可以了
如果系统中很多地方都需要用到echarts,就在main.js中全局引入
import * as echarts from 'echarts'
Vue.prototype.$echarts = echarts