【问题标题】:How can i get the user in firebase database, to write from a component with vuejs?如何让用户在 firebase 数据库中使用 vuejs 从组件中写入?
【发布时间】:2023-03-04 12:24:01
【问题描述】:

希望有人可以帮助我,我是这方面的初学者。 我正在使用 vuejs,firebase,用于从 vue 组件写入数据库。我已经有了授权和写作;但我希望每个用户都写在自己的组件中,而不是所有用户都写在同一个组件中。这是我的代码:

用户登录该组件(login.vue):

<template>
<div>

<h2> auth </h2>

   <div class="container">
   <div class="row">
     <div class="col s12 m8 offset-m2">
       <div class="login card-panel green white-text center">
         <h3>Login</h3>
         <form action="index.html">
           <div class="input-field">
             <i class="material-icons prefix">email</i>
             <input type="email" id="email" v-model="email">
             <label class="white-text" for="email">Email Address</label>
           </div>
           <div class="input-field">
             <i class="material-icons prefix">lock</i>
             <input type="password" id="password" v-model="password">
             <label class="white-text" for="password">Password</label>
           </div>
           <button v-on:click="login" class="btn btn-large btn-extended 
            grey lighten-4 black-text">Login</button>
         </form>
       </div>
     </div>
   </div>
   </div>
  </div>
</template>

<script>
import firebase from 'firebase';
export default {
name: 'login',
data: function() {
 return {
  email: '',
  password: ''
 };
},
methods: {
login: function(e) {
  firebase
    .auth()
    .signInWithEmailAndPassword(this.email, this.password)
    .then(
      user => {
        alert(`You are logged in as ${user.email}`);
        this.$router.go({ path: this.$router.path });
      },
      err => {
        alert(err.message);
      }
    );
  e.preventDefault();
 }
}
};
</script>

然后在这个 (envio.vue) 组件中,用户编写并发送到 firebase:

<template>
 <div id="app">
  <form @submit.prevent="enviarMensaje">
      <textarea v-model="boton1" cols="30" rows="1"></textarea>
      <br>
      <textarea v-model="mensaje" cols="30" rows="10"></textarea>
      <br>
      <input type="submit" value="Enviar mensaje">
  </form>
  <hr>
  <h1>texto con idicaciones</h1>
 </div>
</template>


<script>
import firebase from 'firebase'
import { contenidoFormulario } from '../firebase'

 export default {
  data: function() {
  return {
  mensaje: null,
  boton1: null,
  usuario: '',
  }
 },

 methods: {
  enviarMensaje(){
   contenidoFormulario(uid).set({
      mensaje: this.mensaje,
      boton1: this.boton1,
      usuario: this.usuario,
   })
  }
 }
}
</script>

这是 firebase 数据库 json:

https://xxxxxxx.firebaseio.com/

项目

-- 公式rioContenido:

     boton1: "..."

     mensaje: "..."

     usuario: "..."

我需要这样的东西:

项目

-- 公式rioContenido:

     --user A

          boton1: "..."

          mensaje: "..."

          usuario: "..."

     --user B

          boton1: "..."

          mensaje: "..."

          usuario: "..."

'../firebase' 代码:

import { initializeApp } from 'firebase';



const app = initializeApp({
    apiKey: """",
    authDomain: """
    databaseURL: "",
    projectId: "",
    storageBucket: ""
    messagingSenderId: ""
});


export const db = app.database();
export const contenidoFormulario = db.ref('formularioContenido');

main.js

let app;
firebase.auth().onAuthStateChanged(user => {
  if (!app) {

   app = new Vue({
   el: '#app',
   data: {uid: null}, 
   router,
   template: '<App/>',
   components: { App }
 });

} });

我的退出:

<template>
<div id="app">
<section>

   //...

  <li v-if="isLoggedIn"><button v-on:click="logout" class="btn 
   black">Logout</button></li>

</section>
</div>
</template>

<script>
import firebase from 'firebase';
export default {
  name: 'navbar',
  data() {
   return {
    isLoggedIn: false,
    currentUser: false,
  };
 },
  created() {
    if (firebase.auth().currentUser) {
     this.isLoggedIn = true;
     this.currentUser = firebase.auth().currentUser.email;
  }
 },
  methods: {
   logout: function() {
     firebase
     .auth()
     .signOut()
     .then(() => {
      this.$root.uid = null;   //just added
      this.$router.go({ path: this.$router.path });
     });
    }
   }
  };

  </script>

【问题讨论】:

  • “我希望每个用户都写在自己的组件中”是什么意思?您在这句话中指的是视图组件吗?还是更多到“附加”到用户的特定数据库节点?目前尚不清楚您要做什么。另外,您如何调用 enviarMessaje 方法?调用这个函数时uid参数的值是多少?
  • 感谢@RenaudTarnec 的提问,这个
  • 然后显示更多代码。显示您从 firebase 获取的代码以及您尝试修改的数据。您用来保存它的代码等。对于初学者。
  • @acdcjunior thnxs,我刚刚做到了。
  • '../firebase' 文件中显示contenidoFormulario 定义

标签: javascript firebase firebase-realtime-database vue.js


【解决方案1】:

您必须在登录时保存uid,以便以后使用。

处理这个问题的最佳方法是使用 Vuex,但是,如果对您的应用没有更好的了解,最简单的方法就是在根组件的 data 中创建一个 uid 属性,例如。

// probably main.js file
new Vue({
  el: "#app",
  data: {uid: null}, // added this
  components: { App },
  template: "<App/>"
});

那么它将在全球范围内可用:

this.$root.uid

您可以将其更新为:

this.$root.uid = 'newUserId';

这样的话,你可以认为,如果设置了$root.uid,那么用户就已经登录了。

所以,要设置它,请更改您的登录方法:

methods: {
login: function(e) {
  firebase
    .auth()
    .signInWithEmailAndPassword(this.email, this.password)
    .then(
      user => {
        alert(`You are logged in as ${user.email}`);
        this.$root.uid = user.uid;                       // added this
        this.$router.go({ path: this.$router.path });
      },
      err => {
        alert(err.message);
      }
    );
  e.preventDefault();
 }
}

然后把contenidoFormulario变成这样的函数:

export const contenidoFormulario = (uid) => db.ref('formularioContenido/' + uid);

并且,在组件中使用它时,请执行以下操作:

 methods: {
  enviarMensaje(){
   contenidoFormulario(this.$root.uid).set({        // changed here
      mensaje: this.mensaje,
      boton1: this.boton1,
      usuario: this.usuario,
   })
  }
 }

应该可以的。


注意:不要忘记在代码中的某个位置添加this.$root.uid = null; 以用于注销

注意[2]:由于您使用的是 Firebase,我建议您查看 vuefire。它使集成变得更加容易。

【讨论】:

  • 编辑:$uid 重命名为 uid。当以$ 为前缀时,vue 从选项中获取。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 2022-01-01
相关资源
最近更新 更多