安装:npm install echarts --save
方式一:直接在组件中引用
javascript<template> <div ref="myChart" id="myChart" :style="{ width: '800px', height: '400px' }" ></div> </template> <script> 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>
方式二:在main.js中挂载,如何再组件中使用
javascriptimport { createApp } from 'vue' import App from './App.vue' // 引入 echarts import * as echarts from 'echarts' const app = createApp(App) // 全局挂载 echarts app.config.globalProperties.$echarts = echarts app.mount('#app')
选项式api语法:
javascript<template> <div ref="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>
组合式api语法
javascript<template> <div ref="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: [120, 200, 150, 80, 70, 110, 130], type: 'bar' } ] }; // 设置实例参数 myChart.setOption(option); }); return {}; } }; </script>