【问题标题】:How to retrive the data from a nasted JSON FireBase Database using Vue.js?如何使用 Vue.js 从嵌套的 JSON FireBase 数据库中检索数据?
【发布时间】:2019-10-01 23:59:08
【问题描述】:

我有一个问题,无法使用 Vue.js 从我的 FireBase 数据库中检索数据。

我想检索特定的字段消息和时间戳。 此外,userModel 的名称和电子邮件。 通过了解这一点,我相信我也可以弄清楚如何检索其他人。

我已经成功地使用了简单的数据库。

但是,在我尝试使用 v-for 和键在我的真实数据库上使用嵌套代码执行此操作后,它没有成功,因为我不知道要在 <script> 标记内写入的确切代码。

此外,我相信这可以通过循环来完成,foreach 然后必须连接以从 JSON 树中的字段中获取正确的数据,如下所述?

了解 FireBase 配置,一切都很好。我可以登录我称之为“仪表板”。 在仪表板上,我只想获取并显示 HTML <table> 标记中的数据。

我的 JSON 如下所示:

{
  "chatmodel" : {
    "-LeZnCBPC7FvqMeIfw_Y" : {
      "file" : {
        "name_file" : "some_file.jpg",
        "size_file" : "5332138",
        "type" : "img",
        "url_file" : "https://firebasestorage.googleapis.com/v0/b/xmnovimarof.appspot.com/o/images%2F2019-05-11_045028camera.jpg_camera?alt=media&token=5e13c9be-b6a5-43cb-a4ed-725148d8d3de"
      },
      "message" : "",
      "timeStamp" : "1557543050279",
      "userModel" : {
        "email" : "user@gmail.com",
        "id" : "pQe9H83cxDd8hFu6bFzzt7M5YT12",
        "name" : "First Last Name",
        "phoneNumber" : "+385123456789",
        "photo_profile" : "https://lh4.googleusercontent.com/-Tf1LtwPEmHI/AAAAAAAAAAI/AAAAAAAANnw/fEXJ05bKSPc/s96-c/photo.jpg"
      }
    },
    "-LeZnGUXcNhSYzZeGJWk" : {
      "mapModel" : {
        "latitude" : "46.31",
        "longitude" : "16.33"
      },
      "timeStamp" : "1557543067886",
      "userModel" : {
        "email" : "user@gmail.com",
        "id" : "pQe9H83cxDd8hFu6bFzzt7M5YT12",
        "name" : "First Last Name",
        "phoneNumber" : "+385123456789",
        "photo_profile" : "https://lh4.googleusercontent.com/-Tf1LtwPEmHI/AAAAAAAAAAI/AAAAAAAANnw/fEXJ05bKSPc/s96-c/photo.jpg"
      }
    },
    "-LeZnNJL27r5NHB8gYzt" : {
      "message" : "This is a text test message.",
      "timeStamp" : "1557543095843",
      "userModel" : {
        "email" : "user@gmail.com",
        "id" : "pQe9H83cxDd8hFu6bFzzt7M5YT12",
        "name" : "First Last Name",
        "phoneNumber" : "+385123456789",
        "photo_profile" : "https://lh4.googleusercontent.com/-Tf1LtwPEmHI/AAAAAAAAAAI/AAAAAAAANnw/fEXJ05bKSPc/s96-c/photo.jpg"
      }
    }
  }
}

我有点困惑应该在 <template> 和 <script> 标记中使用哪个代码。

我只需要从这种数据库中获取数据(它有更多类似的项目)。我不需要编辑或删除它。

感谢您提前提供的帮助。

【问题讨论】:

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


    【解决方案1】:

    一种常见的方法是在组件的created 挂钩中获取数据库,请参阅https://vuejs.org/v2/guide/instance.html#Instance-Lifecycle-Hooks

    您将在下面找到基于标准 Vue.js 设置的简单示例的代码。用你自己的项目配置更新 firebaseConfig.js 文件。

    ma​​in.js

    import Vue from "vue";
    import App from "./App.vue";
    
    Vue.config.productionTip = false;
    
    new Vue({
      render: h => h(App)
    }).$mount("#app");
    

    App.vue

        <template>
          <div id="app">
            <HelloWorld/>
          </div>
        </template>
    
        <script>
        import HelloWorld from "./components/HelloWorld";
    
        export default {
          name: "App",
          components: {
            HelloWorld
          }
        };
        </script>
    
        <style>
        #app {
          font-family: "Avenir", Helvetica, Arial, sans-serif;
          -webkit-font-smoothing: antialiased;
          -moz-osx-font-smoothing: grayscale;
          color: #2c3e50;
          margin-top: 60px;
        }
        </style>
    

    components/HelloWorld.vue

    <template>
      <div class="hello">
        <div v-if="chatItems.length">
          <div v-for="ci in chatItems">
            <h4>{{ ci.messageDate }}</h4>
            <p>{{ ci.userName }} - {{ ci.messageText}}</p>
            <hr>
          </div>
        </div>
        <div v-else>
          <p>There are currently no posts</p>
        </div>
      </div>
    </template>
    
    <script>
    import { db } from "../firebaseConfig.js";
    export default {
      name: "HelloWorld",
      data() {
        return {
          chatItems: []
        };
      },
      created() {
        db.ref("chatmodel")
          .once("value")
          .then(dataSnapshot => {
            const itemsArray = [];
            dataSnapshot.forEach(childSnapshot => {
              const childData = childSnapshot.val();
              itemsArray.push({
                messageText: childData.message,
                userName: childData.userModel.name,
                messageDate: childData.timeStamp
              });
            });
            this.chatItems = itemsArray;
          });
      }
    };
    </script>
    
    <!-- Add "scoped" attribute to limit CSS to this component only -->
    <style scoped>
    h3 {
      margin: 40px 0 0;
    }
    ul {
      list-style-type: none;
      padding: 0;
    }
    li {
      display: inline-block;
      margin: 0 10px;
    }
    a {
      color: #42b983;
    }
    </style>
    

    firebaseConfig.js

    import firebase from "firebase";
    
    // Your web app's Firebase configuration
    var firebaseConfig = {
      apiKey: "xxxxxxx",
      authDomain: "xxxxxxx",
      databaseURL: "xxxxxxx",
      projectId: "xxxxxxx",
      storageBucket: "xxxxxxx",
      messagingSenderId: "xxxxxxx",
      appId: "xxxxxxx"
    };
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
    
    const db = firebase.database();
    
    export { db };
    

    【讨论】:

    • 好的,我试试看。感谢您的详细反馈。如果成功,我会将其标记为答案。
    • 谢谢!我一直在寻找相同的,只是不同的数据库模型,但也是嵌套的。
    猜你喜欢
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 2017-02-12
    • 2019-03-25
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多