環境準備
まず、Vueプロジェクトを初期化します。ターミナルで vue create chart-app を実行し、生成されたプロジェクトディレクトリに移動します。次に、EChartsをインストールします。
npm install echarts --save
# または
yarn add echarts
インストールが完了したら、EChartsをプロジェクトに組み込むことができます。以下に、EChartsを使用するいくつかの方法を紹介します。
1. グローバル登録による利用
まず、main.jsファイルでEChartsをインポートし、Vueプロトタイプに登録します。
import * as echarts from 'echarts'
Vue.prototype.$chartLib = echarts;
これにより、任意のコンポーネントでEChartsを使用できるようになります。次に、サンプルコンポーネントでグラフを設定してみましょう。
<template>
<div>
<div class="chart-container" ref="graphArea"></div>
</div>
</template>
<script>
export default {
data() {
return {};
},
methods: {
setupChart() {
const chartInstance = this.$chartLib.init(this.$refs.graphArea);
// グラフオプションの設定
chartInstance.setOption({
title: { text: 'Vue.jsでのECharts利用例' },
tooltip: {},
xAxis: {
data: ["Tシャツ", "セーター", "シャツ", "パンツ", "ハイヒール", "靴下"]
},
yAxis: {},
series: [{
name: '販売数',
type: 'bar',
data: [15, 25, 40, 15, 12, 28]
}]
});
}
},
mounted() {
this.setupChart();
}
}
</script>
<style scoped>
.chart-container {
width: 500px;
height: 500px;
}
</style>
この方法により、プロジェクト全体でEChartsを利用できるようになります。
2. コンポーネント単位での利用
多くの場合、EChartsをグローバルに登録する必要はありません。特定のコンポーネント内でのみ使用する方が効率的です。
<template>
<div>
<div class="chart-box" ref="chartElement"></div>
</div>
</template>
<script>
import { init } from 'echarts';
export default {
data() {
return {};
},
methods: {
createVisualization() {
const chartDom = this.$refs.chartElement;
const myChart = init(chartDom);
// ビジュアライゼーション設定
myChart.setOption({
title: { text: 'コンポーネント内でのECharts利用' },
tooltip: {},
xAxis: {
data: ["ジャケット", "コート", "ドレス", "ジーンズ", "スニーカー", "帽子"]
},
yAxis: {},
series: [{
name: '在庫数',
type: 'bar',
data: [30, 45, 25, 50, 35, 20]
}]
});
}
},
mounted() {
this.createVisualization();
}
}
</script>
<style scoped>
.chart-box {
width: 500px;
height: 500px;
}
</style>
このアプローチでは、EChartsを直接コンポーネント内にインポートします。他のコンポーネントでEChartsを使用する場合は、それぞれのコンポーネントで個別にインポートする必要があります。