1、安装Echarts
npm install echarts --save
2、全局引入
main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import * as echarts from 'echarts'
const app = createApp(App)
app.config.globalProperties.$echarts = echarts // 全局挂载echarts
app.use(store).use(router).mount('#app')
组件中使用
<template>
<div>
<div class="canvars" ref="myRef"></div>
</div>
</template>
<script>
import { ref, onMounted, getCurrentInstance } from 'vue'
export default {
setup() {
const { proxy } = getCurrentInstance() // 获取全局配置项
const myRef = ref(null) // 获取dom实例
onMounted(() => {
renderChart() // 生命周期挂载函数渲染图表
})
const renderChart = () => {
const myChart = proxy.$echarts.init(myRef.value)
myChart.setOption({
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
xAxis: {
data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
},
yAxis: {},
series: [
{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}
]
})
}
return {
myRef
}
}
}
</script>
<style scoped>
.canvars {
width: 200px;
height: 200px;
}
</style>
3、局部引用
<template>
<div>
<h5>资产监控</h5>
<div class="canvars" ref="myRef"></div>
</div>
</template>
<script>
import * as echarts from 'echarts'
import { ref, onMounted } from 'vue'
export default {
setup() {
const myRef = ref(null) // 获取dom实例
onMounted(() => {
renderChart() // 生命周期挂载函数渲染图表
})
const renderChart = () => {
const myChart = echarts.init(myRef.value)
myChart.setOption({
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
xAxis: {
data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
},
yAxis: {},
series: [
{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}
]
})
}
return {
myRef
}
}
}
</script>
<style scoped>
.canvars {
width: 200px;
height: 200px;
}
</style>
setup语法糖写法
<template>
<div>
<div id="canvas" ref="canvas"></div>
</div>
</template>
<script setup>
import { ref, getCurrentInstance, onMounted, onUnmounted } from 'vue';
const { proxy } = getCurrentInstance()
const canvas = ref() // dom实例
let myChart = null // echarts实例
onMounted(() => {
renderChart()
})
const renderChart = () => {
myChart = proxy.$echarts.init(canvas.value)
myChart.setOption({
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data: ['销量']
},
xAxis: {
data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
},
yAxis: {},
series: [
{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}
]
});
}
</script>
<style lang='less' scoped>
#canvas {
width: 300px;
height: 300px;
}
</style>