LoginSignup
0
0

More than 3 years have passed since last update.

Nuxt.js + Firebase + VuexFireでデータ表示をソートする

Last updated at Posted at 2020-05-25

Nuxt.js+Firebaseの勉強を始めたばかりです。
FirestoreのデータをWebページに表示できるようになりました。

前回: FirebaseのセキュリティルールをWHEREのように使えると思っていた

やりたいこと

Firestoreのデータを取得してWebページに表示するためにVuexFireを利用しています。今回は、画面の表示内容をソートしたいです。

環境

  • Firebase 7.3.0
  • Vue CLI 4.0.5
  • Nuxt.js 2.10.2
  • VuexFire 3.2.0

順序の設定はorderByを使う

Firestoreの構成は次の通りです。

コレクション ドキュメント サブコレクション フィールド
notes (uid) pages title

サブコレクションをtitleの降順にするため、 .orderBy('title', 'desc') としています。

  • ~/pages
    • index.vue
  • ~/store
    • index.js
pages/index.vue
    <v-flex
      v-for="page in pages"
      xs12 mb-2>
      <v-card>
        <v-card-text>
          {{page.title}}
        </v-card-text>
      </v-card>
    </v-flex>

  computed: {
    ...mapGetters({ pages: 'getPages' }),
  },
  mounted () {
    let userID = this.$store.getters['auth/getUid'];
    this.$store.dispatch(
      'setPagesRef',
      db.collection('notes').doc(userID)
      .collection('pages').orderBy('title', 'desc'));
  },
store/index.js
import { vuexfireMutations, firestoreAction } from 'vuexfire';
import createPersistedState from "vuex-persistedstate";

export const state = () => ({
      pages: [],
    });

export const mutations = {
      ...vuexfireMutations
    };

export const getters = {
      getPages: (state) => {
        return state.pages;
      },
    };

export const actions = {
      nuxtClientInit ({ commit, state, dispatch }, { req }) {
        createPersistedState()(this);
      },
      setPagesRef: firestoreAction(({ bindFirestoreRef }, ref) => {
        bindFirestoreRef('pages', ref);
      }),
    };
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