概要
Nuxt.js v2でのモジュールモードでaxiosを使ったシンプルなサンプルがないので作ってみました。v3でクラシックモードは廃止になりますし。
モジュールモードはここを参考。
https://qiita.com/y-miine/items/028c73aa3f87e983ed4c
サンプルはここのお天気サンプルをモジュールモードに書き直してみました。
https://qiita.com/kawa64372358/items/02348536eea1881676e8
詳細はコードのコメントでわかると思います。
コード
モジュールモードではexportだけでstoreを記述するのがポイント。
store/index.js
import axios from 'axios';
//データを定義
export const state = () => ({//stateは必須
weather:null //データ
});
//データの更新系を定義。関数で定義
export const mutations = {
updateWeather (state, weather) {
state.weather = weather;//データの更新
}
}
//外部からのコールイベントを定義。関数で定義
export const actions = {
//通信
async fetchWeather({commit}){
const res = await axios.get(`http://weather.livedoor.com/forecast/webservice/json/v1?city=400040`).catch((err) => {
throw new Error(err);
});
// レスポンスがコンソールに表示
console.log(res.data);
commit('updateWeather', res.data);//mutations経由でデータを更新
}
}
components/Pages/ForcastCard/index.vue
<template>
<div class="forcast-list">
<h2 class="forcast-list__title">{{ forecast.dateLabel }}</h2>
<dl>
<dt class="forcast-list__telop">{{ forecast.telop }}</dt>
<dt>
<img
v-show="forecast.image.url"
:src="forecast.image.url"
class="forcast-list__image"
alt="forcast.image.title">
</dt>
</dl>
</div>
</template>
<script>
export default {
//親のvueから値をpropsで受け取る
props: {
forecast: {
type: Object,
required: true
}
}
};
</script>
pages/index.vue
<template>
<section class="weather">
<h1 class="weather__title">{{weather.title}}</h1>
<ForcastCard
v-for="(forecast, i) in weather.forecasts"
:forecast="forecast"
:key="`weather__forcasts-key-${i}`"/>
</section>
</template>
<script>
//自作コンポーネント取り込み
import ForcastCard from '~/components/Pages/ForcastCard';
//バインディング機能
import { mapState, mapMutations, mapActions } from 'vuex'
export default {
//コンポーネントを定義
components: {
ForcastCard
},
//キャッシュされる計算を定義。おもにバインディングで使う
computed: {
//バインディングの情報をここで配列で指定。バインディングがなければ$store.state.xとかでアクセス可能。
...mapState(['weather']),
...mapActions(['fetchWeather'])
},
//通信実行。表示で即時実行
async asyncData({ store, params }) {
await store.dispatch('fetchWeather');
}
};
</script>