vue專案中引用echarts的全域性和區域性方式
vue專案中引用echarts的幾種方式
準備工作:
首先我們初始化一個vue專案,執行vue init webpack echart,接著我們進入初始化的專案下。安裝echarts,
- npm install echarts -S //或
- cnpm install echarts -S
安裝完成之後,我們就可以開始引入我們需要的echarts了,接下來介紹幾種使用echarts的方式。
全域性引用:
首先在main.js中引入echarts,將其繫結到vue原型上:
- import echarts from 'echarts'
- Vue.prototype.$echarts = echarts;
接著,我們就可以在任何一個元件中使用echarts了,接下來我們在初始化專案中的helloWorld元件中使用echarts配置圖示,具體如下:
<template>
<div>
<div style="width:500px;height:500px" ref="chart"></div>
</div>
</template>
<script>
export default{
data () {
return {};
},
methods: {
initCharts () {
let myChart = this.$echarts.init(this.$refs.chart);
console.log(this.$refs.chart)
// 繪製圖表
myChart.setOption({
title: { text: '在Vue中使用echarts' },
tooltip: {},
xAxis: {
data: ["襯衫","羊毛衫","雪紡衫","褲子","高跟鞋","襪子"]
},
yAxis: {},
series: [{
name: '銷量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
});
}
},
mounted () {
this.initCharts();
}
}
</script>
這樣下來,就可以在專案的任何地方使用echarts了。
區域性使用:
當然,很多時候沒必要在全域性引入ecahrts,那麼我們只在單個元件內使用即可,程式碼更加簡單:
<template>
<div>
<div style="width:500px;height:500px" ref="chart"></div>
</div>
</template>
<script>
const echarts = require('echarts');
export default{
data () {
return {};
},
methods: {
initCharts () {
let myChart = echarts.init(this.$refs.chart);
// 繪製圖表
myChart.setOption({
title: { text: '在Vue中使用echarts' },
tooltip: {},
xAxis: {
data: ["襯衫","羊毛衫","雪紡衫","褲子","高跟鞋","襪子"]
},
yAxis: {},
series: [{
name: '銷量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
});
}
},
mounted () {
this.initCharts();
}
}
</script>
可以看到,我們直接在元件內引入echarts,接下來跟全域性引入的使用一樣。區別在於,這種方式如果你想在其他元件內用echarts,則必須重新引入了。