1
0
hugo/content/blog/2020-04-12-vue.md
2024-04-23 22:21:26 +09:00

109 lines
3.1 KiB
Markdown

+++
date = "2020-04-12JST"
tags = ["vue"]
title = "vueでapexchartsを使いチャートを作ってみた"
slug = "vue"
+++
chart.jsが有名みたいで、ちょっと触ってチャートを表示してみたのですが、非常に操作しづらかったので、apexchartsを使ってみました。個人的には、こちらのほうがオススメかも。
```sh
# https://github.com/apexcharts/vue-apexcharts
$ yarn add apexcharts vue-apexcharts
```
今回作ったのは、vue+apexcharts+axiosという構成で、毎日更新されてるぽいcovid-19のjsonがあるのですが、値をとってきてチャートで表示することにしてみました。
https://syui.cf/covid-vue-chart
```sh
$ git clone https://github.com/syui/covid-vue-chart
$ cd !$:t
$ yarn install
$ yarn serve
```
```js:src/main.js
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`して表示してます。これはなくてもいい。
```html:src/App.vue
<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、楽しかったので、今日もついつい触ってしまいました。