update : 0001-01-01
2020-04-12 / @syui

vue

vueでapexchartsを使いチャートを作ってみた

chart.jsが有名みたいで、ちょっと触ってチャートを表示してみたのですが、非常に操作しづらかったので、apexchartsを使ってみました。個人的には、こちらのほうがオススメかも。

# https://github.com/apexcharts/vue-apexcharts
$ yarn add apexcharts vue-apexcharts

今回作ったのは、vue+apexcharts+axiosという構成で、毎日更新されてるぽいcovid-19のjsonがあるのですが、値をとってきてチャートで表示することにしてみました。

https://syui.cf/covid-vue-chart

$ git clone https://github.com/syui/covid-vue-chart
$ cd !$:t
$ yarn install
$ yarn serve
import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
import VueApexCharts from 'vue-apexcharts'

Vue.component('apexchart', VueApexCharts)
Vue.config.productionTip = false
Vue.use(VueAxios, axios, VueApexCharts)

new Vue({
  render: h => h(App)
}).$mount('#app')

内容は非常にシンプルで以下のような書き方になりました。axiosでjsonを取ってきて配列に入れてあげる感じ。あと、type:lineがやりたくてoptionかなあと思ったのですが、vue-apexchartは、htmlでtype="line"みたいです。

チャートを作成するときは、jsonのkeyやら確認する必要がありますので、this.items = res.dataして表示してます。これはなくてもいい。

<template>
	<div id="covid19">
		<h1>covid19</h1>
		<div>
			<apexchart width="95%" type="line" :options="chartOptions" :series="series"></apexchart>
		</div>
		<div v-for="(item, idx) in items" v-bind:key="idx">
			<li  v-if="idx === 'Japan'">
				{{ idx }} {{ item }}
			</li>
		</div>
	</div>
</template>

<script>
import axios from 'axios';
export default {
	created(){
		axios.get('https://raw.githubusercontent.com/pomber/covid19/master/docs/timeseries.json').then((res) => {
			var confirmed = []
			var confirmedt = []
			var date = []
			res.data.Japan.forEach(function (key) {
						confirmed.push(key.confirmed)
			})
			res.data.Thailand.forEach(function (key) {
						confirmedt.push(key.confirmed)
			})
			res.data.Japan.forEach(function (key) {
						date.push(key.date)
			})
			this.series = [{ data: confirmed },{ data: confirmedt }]
			this.chartOptions = {
				xaxis: { 
					categories:	date
			}}
			this.items = res.data
		}).catch((error) => {
			console.error(error)
		})
	},
	data () {
		return {
			chartOptions: {
				chart: {
					id: 'vuechart-example'
				},
				xaxis: {
					categories: [] 
				}
			},
			series: [ {name: "japan", data: [] }, {name: "Thailand", data: [] } ]
		}
	}
}
</script>

注意点としては、gh-pagesは、サブディレクトリになるので、vue.config.jsでpublicPathを設定してやることです。index.htmlのlink pathが/なので。

昨日、マンガのやつでちょっとだけvueを触ったこともあり、vue、楽しかったので、今日もついつい触ってしまいました。