Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

const db = firebase.firestore();をinportできるようにしたい

前提・実現したいこと

nuxt.jsとfirebaseを使って道場生管理アプリを作っています。ディレクトリ構成は以下です。

├── components
│ ├──profile
│    ├──name.vue
│ ├──kana.vue
│ :
├──pages
│ ├── add.vue
│ └── index.vue
├── plugins
│ ├── firebase.js

└── store
├── add.js
└── index.js

index.jsとadd.js以下のファイルは親子関係にあります。
道場生の登録画面であるadd.vueでうった情報をindex.vueで表示させたいのですが、index.vueに表示されません。
原因を突き詰めていくとどうやらfirebase.firestore()がきちんとimportできていないのが原因ぽいですが何故importできないのかわからず困っています。

発生している問題・エラーメッセージ

add2.vue

const db = firebase.firestore()
をadd.vueにかくと
client.js?06a0:97 TypeError: Cannot read property 'firestore' of undefined
書かないと
client.js?06a0:97 TypeError: studentsRef.add is not a function と出る。

該当のソースコード

add.vue

<template>
  <v-app>
    <v-main>
      <v-container>
        <v-row>
          <v-col>
            <v-row justify="center">
              <v-icon class="ml-5">
                mdi-account
              </v-icon>
              <h1 class="ml-5">生徒管理</h1>
              <v-spacer></v-spacer>
            </v-row>
            <v-divider color="blue"/>
          </v-col>
        </v-row>
          <ValidationObserver ref="observer" v-slot="{ invalid }" immediate>
            <v-form  @submit.prevent="registration" v-model="valid">
             <!-- <Name @send_name='sendName' /> -->
             <v-row class="ml-5 mt-1" dense>
    <!-- 道場生の姓名入力 -->
    <v-col cols="2">
      <ValidationProvider v-slot="{ errors, valid}" name="姓" rules="required|zenkaku">
        <v-badge left color="error" content="必須">
          <v-text-field
          label="姓"
          outlined
          placeholder="田中"
          v-model="familyName"
          required
          :error-messages="errors"
          :success="valid"/>
        </v-badge>
      </ValidationProvider>
    </v-col>
    <v-col cols="2">
      <ValidationProvider v-slot="{ errors, valid }" name="名" rules="required|zenkaku">
          <v-text-field
          label="名"
          outlined
          placeholder="太郎"
          v-model="firstName"
          required
          :error-messages="errors"
          :success="valid"/>
      </ValidationProvider>
    </v-col>
    <v-col/>
    <!-- 保護者氏名入力 -->
    <v-col cols="2">
      <ValidationProvider v-slot="{ errors, valid}" name="保護者姓" rules="required|zenkaku">
        <v-badge left color="error" content="必須">
          <v-text-field
          label="保護者姓"
          outlined
          placeholder="田中"
          v-model="parentsFamilyName"
          required
          :error-messages="errors"
          :success="valid"/>
        </v-badge>
      </ValidationProvider>
    </v-col>
    <v-col cols="2">
      <ValidationProvider v-slot="{ errors, valid}" name="保護者名" rules="required|zenkaku">
        <v-text-field
        label="保護者名"
        outlined
        placeholder="次郎"
        v-model="parentsFirstName"
        required
        :error-messages="errors"
        :success='valid'/>
      </ValidationProvider>
    </v-col>
    <v-col/>
  </v-row>
                <v-row dense>
                  <v-col justify="center" align="center">
                    <v-btn type="submit" nuxt color="success" :disabled="invalid">送信</v-btn>
                  </v-col>
                </v-row>
            </v-form>
          </ValidationObserver>
      </v-container>
    </v-main>
  </v-app>
</template>

<script>
import { mapActions } from 'vuex'
import { db } from '~/plugins/firebase.js'
import { firebase } from '~/plugins/firebase.js'
import { ValidationObserver, ValidationProvider } from 'vee-validate'
import Name from '~/components/profile/Name.vue'
export default {
  components : {
    ValidationObserver,
    ValidationProvider,
    Name
  },
  data() {
    return {
      valid: false,
      familyName: '',
      firstName: '',
      parentsFamilyName: '',
      parentsFirstName: '',
    }
  },
  // created: {
  //   sendName() {
  //     return ({firstName: this.firstName, familyName:this.familyName})
  //   }
  // },
  methods: {
      async registration() {
          const student = {
            familyName: this.familyName,
            firstName: this.firstName
        }
        const db = firebase.firestore() //これを入れるか入れないかでエラー内容が変わる。
        const studentsRef =  db.collection('students').doc('生徒一覧')
        await studentsRef.add(student)
        console.log(student)
        // this.$router.push(`/`)
        this.familyName = ''
        this.firstName = ''
        // await this.$store.dispatch('signUp',this.firstName)
        // this.familyName = ''
        // this.firstName = ''
      },

  },
}
</script>

firebase.js

import * as firebase from "firebase/app";
import 'firebase/auth'
import 'firebase/firestore'

const firebaseConfig = {
  
};


firebase.initializeApp(firebaseConfig);
export default firebase;
const db = firebase.firestore();
export { db }

試したこと

記事を参照し、コピペしていますのでタイポミスはないように思います。

補足情報(FW/ツールのバージョンなど)

ここにより詳細な情報を記載してください。

0 likes

2Answer

import { firebase } from '~/plugins/firebase.js'

ではなく、

import firebase from '~/plugins/firebase.js'

理由については、デフォルトエクスポートとネームドエクスポートについて調べてみると良いと思います!

0Like

Comments

  1. @wantyan

    Questioner

    回答ありがとうございます。デフォルトエクスポートとネームドエクスポートについて調べて実践してみましたが結果は変わらずです。

まず、dbはプラグインからインポートしているのでadd.vue内でdb =...は不要です。

次に、エラーの通りdoc(...)の戻り値オブジェクトにadd関数は定義されていないようです。
(collectionに対しては"add"、documentに対しては"set")
以下でいかがでしょうか?

const studentsRef = db.collection('students')
await studentsRef.add(student)

※上記の場合studentsコレクションに新しいドキュメントが生成されます。データ構成は想定通りですか?

余談ですが関数や定数が定義されているかが分かるTypeScriptの使用をオススメします。

0Like

Your answer might help someone💌