一、业务场景:
最近在vue中使用echarts时 引入的时候怎么也引不上,后面发现需要绑定在原型上就可以完美解决(也可以直接在需要引入的页面用ES5中的require引入require(‘echarts’))
为了避免大家走弯路,下面整合了一下echarts 在vue框架中的使用步骤
二、具体实现步骤:
1、先在终端安装echarts
npm install echarts --save
2、在main.js中引入(这里分5.0以上和以下两个版本来安装)
5.0以上版本
import * as echarts from 'echarts'
5.0以下版本
import echarts from 'echarts'
注册在原型上 `
vue.prototype.$echarts = echarts
3、在html部分留一个div容器来承载画布
<div id="main" style="width: 600px;height:400px;"></div>
4、把要实现的代码放入函数中
init() {
// 基于准备好的dom,初始化echarts实例
var myChart = this.$echarts.init(
document.getElementById("main")
);
// 配置option选项
var option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [150, 230, 224, 218, 135, 147, 260],
type: 'line'
}
]
};
// 把配置option选项用js放进dom节点
myChart.setOption(option);
}
5、页面加载的时候调用功能函数(mounted生命周期里)
mounted() {
this.init()
},
三、完整代码:
<template>
<div>
<div id="main" style="width: 600px;height:400px;"></div>
</div>
</template>
<script>
export default {
name: 'WhiteName',
data() {
return {}
},
mounted() {
this.init()
},
methods: {
init() {
// 基于准备好的dom,初始化echarts实例
var myChart = this.$echarts.init(
document.getElementById("main")
);
// 配置option选项
var option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [150, 230, 224, 218, 135, 147, 260],
type: 'line'
}
]
};
// 把配置option选项用js放进dom节点
myChart.setOption(option);
}
}
}
</script>
<style scoped>
</style>
四、效果展示:
你已经成功了,撒花。
今天的分享到此结束,欢迎小伙伴们一起交流