top of page
  • 執筆者の写真T sakurako

VueでWEBアプリ(23)

更新日:2021年8月31日

前回書いたように、vuexを用いてデータ管理する形に修正しています。

とりあえず現段階では、一覧データの取得をstore/index.jsでして、それをArticle.vueで表示できるようにしました。


 

store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'


Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    articleList:[]
  },
  mutations: {
    getArticles(state,article_data){
      state.articleList = article_data
    }
  },
  actions: {
    async getArticlesAction(context){
      const response = await axios.get(process.env.VUE_APP_API_URL)
        .catch(error => {
          console.log(error);
      })
      context.commit("getArticles",response.data.data)
    }
  },
  modules: {
  }
})

最初はこちら↓の記事を参考にしていたのですが、


こちらのやり方だと

Syntax Error: Unexpected reserved word 'await'.

のエラーが出てしまったので、この点に関しては

こちら↓の方を参考にすることにしました。


取得時にエラーが出たら、内容が表示されるようにしています。





Article.vue

v-data-tableに入れるにあたり、いったん取得したデータをListに入れています。

これを書いているせいで、async/awaitがないとデータの取得より先に画面が出てしまうので、async mounted()としています。


こちらのstackoverflowの質問を見てこの書き方ができると知りました。

  async mounted() {
    await this.$store.dispatch('getArticlesAction')
    this.List = this.$store.state.articleList
  },

v-data-tableでは、:item="List"に修正しています。

          <v-data-table
            :headers="headers"
            :items="List"
            @click:row="clickRow"
            >
            <!--v-data-tabelのitemsをslotに設定-->
            <template slot="items" slot-scope="props">
              <td class="text-xs-center">{{ props.item.id }}</td>
              <td class="text-xs-center">{{ props.item.title }}</td>
              <td class="text-xs-center">{{ props.item.name }}</td>
              <td class="text-xs-center">{{ props.item.post_date }}</td>
              <td class="text-xs-center">{{ props.item.content }}</td>
              <td class="justify-center layout px-0">
              </td>
            </template>
          </v-data-table>



 

この『VueでWEBアプリ』シリーズのコードをgithubで公開しています。参考までに。







閲覧数:8回
記事: Blog2_Post
bottom of page