0
0

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のstore(vuex)でAPIからデータを取得して表示するまで

Last updated at Posted at 2020-08-17

いままで各vueファイルでaxiosを使ってデータ取得してたけど、これで処理を共通化したけどかなり詰まったのでめも。
ひとまず表示はできるようになったとこまで。

actionsの書き方が悪かったっぽく、stateを取得しても[]としか表示されなくて困った。
公式をちゃんと見れば動いた。
https://ja.nuxtjs.org/api/pages-fetch/

vuexってなんぞやはここが参考になった。
https://qiita.com/aya02/items/933c6c55b8e4801f150a

store

参考
https://qrunch.net/@itahana/entries/RV6zu252J67FJpkl?ref=qrunch

store>getjson.js
import axios from 'axios'

export const state = () => ({
  items: []
})

export const mutations = {
  setItems (state, items) {
    state.items = items
  }
}

export const actions = {
  async nuxtServerInit({ commit }) {
    const { data } = await axios.get('APIの取得URL', {withCredentials: true})
    commit('setItems', data)
  }
}

export const getters = {
  getItems: (state) => state.items
}

pages

pages.vue
<template>
  <div>
    <p>{{ data }}</p>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'

export default {
  created(){
    this.$store.dispatch("nuxtServerInit")
  },
  computed:{
    ...mapGetters({
      jsonData: 'getItems'
    })
  },
}
</script>
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?