简体   繁体   English

如何在 Vue.js 和 Firebase 中向现有用户添加新数据

[英]How to add new data to existing user in Vue.js and Firebase

I am attempting to configure a Vue.js app to add additional data to an already-created user in Firebase.我正在尝试配置 Vue.js 应用程序以向 Firebase 中已创建的用户添加其他数据。 I have set up SignUp.vue to set initial input, including the email, password, and name using:我已经设置了 SignUp.vue 来设置初始输入,包括电子邮件、密码和名称,使用:

ref.set({
  name: this.name,
  email: this.email,
  user_id: cred.user.uid
})

In Home.vue, I included an input field with the following method to add the input to the currently-logged in user in the database:在 Home.vue 中,我包含了一个输入字段,使用以下方法将输入添加到数据库中当前登录的用户:

async addInput () {
    let ref = await db.collection('users')
    ref.where('user_id', '==', firebase.auth().currentUser.uid).add({
        newInput: this.newInput
    })
}

However, this still did not work.然而,这仍然没有奏效。 Any recommendations on how to add input to an existing user?关于如何向现有用户添加输入的任何建议?

See full code below:请参阅下面的完整代码:

SignUp.vue注册.vue

<template>
    <div class="sign-up">
        <p>Let's create a new account!</p>
        <input type="text" v-model="email" placeholder="Email" />
        <br />
        <input type="password" v-model="password" placeholder="Password" />
        <br />
        <input type="text" v-model="name" placeholder="Name" />
        <br />
        <v-btn @click="signUp" color="info">Sign Up</v-btn>
        <span>
            or go back to
            <router-link to="/login">login</router-link>.
        </span>
    </div>
</template>

<script>
import slugify from "slugify";
import firebase from "firebase";
import db from "@/firebase/init";
export default {
    name: "signUp",
    data() {
        return {
            email: "",
            password: "",
            name: ""
        };
    },
    methods: {
        signUp() {
            if (this.name && this.email && this.password) {
                this.slug = slugify(this.name, {
                    replacement: "-",
                    remove: /[$*_+~,()'"!\-:@]/g,
                    lower: true
                });
                let ref = db.collection("users").doc(this.slug);
                ref.get().then(doc => {
                    if (doc.exists) {
                        this.feedback = "This alias already exists";
                    } else {
                        firebase
                            .auth()
                            .createUserWithEmailAndPassword(this.email, this.password)
                            .then(cred => {
                                ref.set({
                                    name: this.name,
                                    email: this.email,
                                    user_id: cred.user.uid
                                });
                            })
                            .then(() => {
                                this.$router.push({ name: "Home" });
                            })
                            .catch(err => {
                                this.feedback = err.message;
                            });
                        this.feedback = "This alias is free to use";
                    }
                });
            } else {
                this.feedback = "You must enter all fields";
            }
        }
    }
};
</script>

Home.vue

<template lang="html">
  <div class="editProfile container">
    <v-app id="inspire">
      <v-container fluid>
        <h1>Update Your Profile!</h1>

        <v-card max-width="344" class="mx-auto">
          <v-card-title>New User Input</v-card-title>
          <v-text-field v-model="newInput"></v-text-field>
          <v-card-actions>
            <v-btn text @click="addInput()">Click</v-btn>
          </v-card-actions>

          <v-list class="elevation-1">
            <v-list-tile-content v-for="user in this.$store.getters.getUsers" :key="user.id" >
              <v-list-tile>
                <textarea v-model="user.newInput" readonly></textarea>
              </v-list-tile>
            </v-list-tile-content>
          </v-list>
        </v-card>

      </v-container>
    </v-app>
  </div>
</template>

<script>
import firebase from "firebase";
import db from "@/firebase/init";
export default {
    name: "home",
    beforeCreate: function() {
        this.$store.dispatch("setCurrentUser");
    },
    data: () => ({
        currentlyEditing: null,
        newInput: null
    }),
    methods: {
        async addInput() {
            let ref = await db.collection("users");
            ref.where("user_id", "==", firebase.auth().currentUser.uid).add({
                newInput: this.newInput
            });
        }
    }
};
</script>

Store.js商店.js

import Vue from 'vue'
import Vuex from 'vuex'
import firebase from 'firebase'
import db from '@/firebase/init'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        users: null
    },
    getters: {
        getUsers: state => {
            return state.users
        }
    },
    mutations: {
        setCurrentUser: state => {
            const users = []
            let ref = db.collection('users')
            ref.where('user_id', '==', firebase.auth().currentUser.uid).get()
                .then(snapshot => {
                    snapshot.forEach(doc => {
                        let currentUserData = doc.data()
                        currentUserData.id = doc.id
                        users.push(currentUserData)
                    })
                    state.users = users
                })
        }
    },
    actions: {
        setCurrentUser: context => {
            context.commit('setCurrentUser')
        }
    }
})

OK, this is ultimately what I was trying to achieve, based on Augusto's feedback.好的,根据奥古斯托的反馈,这就是我最终想要实现的目标。 This function pushes user input into an array in Firebase, which is what I am aiming for.此函数将用户输入推送到 Firebase 中的数组中,这正是我的目标。 However, I want to re-style the output, which currently returns the array container as well to the screen.但是,我想重新设置输出的样式,该输出当前也将数组容器返回到屏幕。 How can I re-style this so that the items in the array are arranged nicely in line items without the array container?如何重新设置样式,以便数组中的项目在没有数组容器的行项目中排列得很好? Preferably with Vuetify.最好使用 Vuetify。 Thanks!谢谢!

    async addInput () {
      let finalInput = this.newInput
      let ref = await db.collection('users').where('user_id', '==', firebase.auth().currentUser.uid)
      .get()
      .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
          console.log(doc.id, " => ", doc.data());
          doc.ref.update({'events': firebase.firestore.FieldValue.arrayUnion(finalInput)})
        })
      })
      .catch(function(error) {
        console.log("Error getting documents: ", error);
      });
    }
<v-list class="elevation-1">
  <v-list-tile-content v-for="user in this.$store.getters.getUsers" :key="user.id" >
    <v-list-tile>
      {{ user.events }}
    </v-list-tile>
  </v-list-tile-content>
</v-list>

Just use update instead add .只需使用update代替add It's definitely will works.它肯定会起作用。

async addInput () {
  this.updates.push(this.newInput)
  let finalInput = this.updates
  let ref = await db.collection('users').where('user_id', '==', firebase.auth().currentUser.uid)
  .get()
  .then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
      console.log(doc.id, " => ", doc.data());
      doc.ref.update({'newInput': finalInput})
    })
  })
  .catch(function(error) {
    console.log("Error getting documents: ", error);
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM