1.下载 echartsnpm i -s echarts
2.在main.js中引入import { createApp } from 'vue'
import App from './App.vue'// 引入 echarts
import * as echarts from 'echarts'
const app = createApp(App)
// 全局挂载 echarts
app.config.globalProperties.$echarts = echartsapp.mount('#app')
3.方式一:vue3.0的写法,在组件中使用<template><divref="myChart"id="myChart":style="{ width: '800px', height: '400px' }"></div>
</template><script>
import { getCurrentInstance, onMounted } from 'vue';export default {setup() {// 通过 internalInstance.appContext.config.globalProperties 获取全局属性或方法let internalInstance = getCurrentInstance();let echarts = internalInstance.appContext.config.globalProperties.$echarts;onMounted(() => {const dom = document.getElementById('myChart');const myChart = echarts.init(dom); // 初始化echarts实例const option = {xAxis: {type: 'category',data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']},yAxis: {type: 'value'},series: [{data: [820, 932, 901, 934, 1290, 1330, 1320],type: 'line',smooth: true}]};// 设置实例参数myChart.setOption(option);});return {};}
};
</script>
4:方式二:全局挂载后,在组件中以 vue2 的写法<template><divref="myChart"id="myChart":style="{ width: '800px', height: '400px' }"></div>
</template>
<script>
export default {mounted() {this.drawLine();},methods: {drawLine() {const dom = this.$refs['myChart'];const myChart = this.$echarts.init(dom); // 初始化echarts实例const option = {xAxis: {type: 'category',data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']},yAxis: {type: 'value'},series: [{data: [820, 932, 901, 934, 1290, 1330, 1320],type: 'line',smooth: true}]};// 设置实例参数myChart.setOption(option);}}
};
</script>
5.方式三:直接在组件中引入echarts<template><divref="myChart"id="myChart":style="{ width: '800px', height: '400px' }"></div>
</template><script>
// 方式二:直接在组件中引入echarts
import * as echarts from 'echarts';
export default {mounted() {const dom = this.$refs['myChart']; // 获取dom节点const myChart = echarts.init(dom); // 初始化echarts实例const option = {xAxis: {type: 'category',data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']},yAxis: {type: 'value'},series: [{data: [820, 932, 901, 934, 1290, 1330, 1320],type: 'line',smooth: true}]};// 设置实例参数myChart.setOption(option);}
};
</script>
————————————————
原文链接:https://blog.csdn.net/weixin_43919509/article/details/120570975