Vue中使用echarts

2020-11-13 11:02:19

使用步驟

  1. 在專案下使用命令列,初始化工程的 npm 環境並安裝 echarts(這裡前提是您已經安裝了 npm):
npm init
npm install echarts --save

2.匯入模組到main.js(如果你只有一個元件都用echarts,那麼就匯入區域性)

全域性

main.js:

import Vue from 'vue'
import echarts from 'echarts'
//需要掛載到Vue原型上
Vue.prototype.$echarts = echarts

之後的元件內部使用:

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

<script>
//通過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>

之後執行即可

區域性

區域性使用:

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

<script>
  import echarts from 'echarts'
  export default {
    name: "echarts",
    data() {
      return {}
    },
    mounted() {
      this.echartsInit()
    },
    methods:{
      echartsInit() {
        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>

<style scoped>

</style>

echarts官網教學:
https://echarts.apache.org/zh/tutorial.html
echarts官網還有更多的範例:
https://echarts.apache.org/examples/zh/index.html

1.進入官網
2.找到你想要的效果
3.點選進入
在這裡插入圖片描述
4.複製程式碼貼上