首页 > 技术文章 > vue中使用echarts

myqinyh 2021-12-29 10:21 原文

1、在项目下使用命令行,初始化工程的 npm 环境并安装 echarts(这里前提是您已经安装了 npm)

npm init
npm install echarts --save

2、全局引入

main.js

import Vue from 'vue'
//全局引入echarts
import * as echarts from 'echarts';
//需要挂载到Vue原型上
Vue.prototype.$echarts = echarts

组件中使用

<template>
  <div style="width: auto;height: 400px" id="main">
  </div>
</template>
//通过this.$echarts来使用
  export default {
    name: "page",
    mounted(){
        // 在通过mounted调用即可
        this.echartsInit()
    },
    methods: {
        //初始化echarts
        echartsInit() {
            //柱形图
            //因为初始化echarts 的时候,需要指定的容器 id='main'
            this.$echarts.init(document.getElementById('main')).setOption({
                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',
                    showBackground: true,
                    backgroundStyle: {
                        color: 'rgba(220, 220, 220, 0.8)'
                    }
                }]
            })
        }
            
    }
  }
</script>

3、局部使用

<template>
  <div style="width: auto;height: 400px" id="main">
  </div>
</template>

<script>
  import * as echarts from 'echarts';
  export default {
    name: "echarts",
    data() {
      return {}
    },
    mounted() {
      this.echartsInit()
    },
    methods:{
      echartsInit() {
     //使用时只需要把setOption里的对象换成echarts中的options或者自己的参数即可 echarts.init(document.getElementById(
'main')).setOption({ 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', showBackground: true, backgroundStyle: { color: 'rgba(220, 220, 220, 0.8)' } }] }) } } } </script>
————————————————
版权声明:本文为CSDN博主「Code。。。」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Soul_guys/article/details/109617069

推荐阅读