3
2

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でのゲッターの使い方

Posted at

まずはストアを作ってgettersの中に定義(クラシックモード使用時)

  • 練習なのでクラシックモードで。。。
  • 今回はitem(配列)を使う場面を想定
index.js
import Vuex from 'vuex';

const store = {
  state: {
    items: [],
  },
  getters: {
    items: state => state.items,
  },

//この辺で実際にitemsの情報をapi通信で取得するイメージ

画面側で使うとき(値を取得してv-forでぶん回して表示する画面のイメージ)

  • 1.<script>の最初でmapGettersをインポートする

  • 2. computedの中でmapGettersヘルパーを使って使いたいゲッターを宣言

  • これでv-forの中でitemsが使えるようになる

index.vue
<template>
  <section class="container">
    <div>
      <h3>Nuxt.js のタグが付けられた投稿の一覧</h3>
      <ul>
        <li v-for="item in items" :key="item.id">//1.
          <h4>
            <span>{{item.title}} </span>
            <small>
              <span>by </span>
              <nuxt-link :to="`/users/${item.user.id}`">
                {{item.user.id}}
              </nuxt-link>
            </small>
          </h4>
        </li>
      </ul>
    </div>
  </section>
</template>
<script>
import { mapGetters } from 'vuex';
export default {
  async asyncData({ store }) {
    if (store.getters['items'].length) {
      return;
    }
    await store.dispatch('fetchItems');
  },
  computed: {
    ...mapGetters(['items'])
  }
};
</script>

次はapi通信について書くぞー。

3
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?