3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Nuxt.js V2環境でモジュールモードで作り直してみた

Last updated at Posted at 2019-05-10

概要

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>

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?