npm install echarts --save
- import * as echarts from 'echarts'
- Vue.prototype.$echarts = echarts
"echart" style="width: 100%;height:300px">
通过id来标识这个组件,这里的样式宽度和高度最好给一个,不然可能会加载不出来。
- methods: {
- drawChart() {
- // 这里的echart同div里的id名相同即可
- const myChart = this.$echarts.init(document.getElementById("echart"));
- // option为一个设置图表格式的数组
- myChart.setOption(this.option);
- },
- },
- mounted() {
- this.drawChart();
- },
其中option就是对于这个图表的设置,官网中给出的例子option就是这个东西
只需要照着官网的示例选取自己需要的option即可。
- option: {
- title: {
- text: "测试用例",
- left: "center",
- },
- tooltip: {
- trigger: "item",
- },
- legend: {
- orient: "vertical",
- left: "left",
- },
- series: [
- {
- name: "数量",
- type: "pie",
- radius: "50%",
- data: [
- { value: 1048, name: "测试用例1" },
- { value: 735, name: "测试用例2" },
- { value: 580, name: "测试用例3" },
- ],
- emphasis: {
- itemStyle: {
- shadowBlur: 10,
- shadowOffsetX: 0,
- shadowColor: "rgba(0, 0, 0, 0.5)",
- },
- },
- },
- ],
- },
- <div>
- <div id="echart" style="width: 100%; height: 300px">div>
- div>
-
- <script>
- export default {
- components: {},
- data() {
- return {
- option: {
- title: {
- text: "测试用例",
- left: "center",
- },
- tooltip: {
- trigger: "item",
- },
- legend: {
- orient: "vertical",
- left: "left",
- },
- series: [
- {
- name: "数量",
- type: "pie",
- radius: "50%",
- data: [
- { value: 1048, name: "测试用例1" },
- { value: 735, name: "测试用例2" },
- { value: 580, name: "测试用例3" },
- ],
- emphasis: {
- itemStyle: {
- shadowBlur: 10,
- shadowOffsetX: 0,
- shadowColor: "rgba(0, 0, 0, 0.5)",
- },
- },
- },
- ],
- },
- };
- },
- created() {
- },
- methods: {
- drawChart() {
- const myChart = this.$echarts.init(document.getElementById("echart"));
- myChart.setOption(this.option);
- },
- },
- mounted() {
- this.drawChart();
- },
- };
- script>
-
- <style scoped lang="less">
- style>
① Error: Initialize failed: invalid dom.
将this.drawChart();放到了create里面,没放到mounted里
② Error in mounted hook: "ReferenceError: echarts is not defined"
没有正确引用echarts,特别是看看引用的那段是否出错,以及main.js中是否全局引用。
const myChart = this.$echarts.init(document.getElementById("echart"));