简体   繁体   English

无法获取Firebase数据以在简单的Vue应用上显示

[英]Can't get Firebase data to display on simple Vue app

I'm trying to get a simple Vue+Firebase app running that allows you to send strings to the firebase database and have the messages be displayed using the "v-for" directive. 我正在尝试运行一个简单的Vue + Firebase应用程序,该应用程序允许您将字符串发送到firebase数据库,并使用“ v-for”指令显示消息。 However, I keep getting the error 但是,我不断收到错误

Property or method "messages" is not defined on the instance but referenced during render

even though I'm pretty sure I'm using the correct syntax based on Vue's example on their site and the Vuefire github page to link up messages to the database. 即使我非常确定我根据他们站点上的Vue示例和Vuefire github页面使用正确的语法来将messages链接到数据库。 I can push to the database just fine, but for some reason I can't read the data from the database. 我可以很好地推送到数据库,但是由于某种原因,我无法从数据库中读取数据。 I've been unable to get this to work for about a day and at this point any help is appreciated. 我一直无法使用这项功能大约一天,因此,我们将不胜感激。

Here is my code for reference: 这是我的代码供参考:

index.html: index.html的:

<head>
    <script src="https://www.gstatic.com/firebasejs/5.2.0/firebase.js"></script>
    <script>
      // Initialize Firebase
      var config = { ... };
      firebase.initializeApp(config);
    </script>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>

<body>
     <div id="app">
      <input type="text" v-model="message" placeholder="Type a message!">
      <button v-on:click="sendData">Send Data</button>
      <br>
      <h3 v-for="msg in messages">{{msg.value}}</h3>
    </div>

    <script type="text/javascript" src="app.js"></script>
</body>

app.js: app.js:

var messageRef = firebase.database().ref('local/responses');

var app = new Vue({
  el: '#app',
  data: function () {
    return {
      message: ''
    }
  },
  firebase: function () {
    return {
      messages: messageRef
    }
  },
  methods: {
    sendData: function () {
      messageRef.push(this.message);
      this.message = '';
    }
  }
});

You need to include the messages property in both the firestore return function as a database reference, as well as the data return function as an empty array for the database to bind to, as such. 您需要在firestore返回函数(包括数据库引用)和data返回函数(作为要绑定到数据库的空数组)中都包含messages属性。

var app = new Vue({
  el: '#app',
  data: function () {
    return {
      message: '',
      messages: []
    }
  },
  firebase: function () {
    return {
      messages: firebase.database().ref('local/responses')
    }
  },
  methods: {
    sendData: function () {
      messageRef.push(this.message);
      this.message = '';
    }
  }
});

This happens because you're trying to bind the Firestore reference to a piece of data that doesn't exist within your Vue instance, it needs that empty array for it to bind to the data property. 发生这种情况是因为您试图将Firestore引用绑定到Vue实例中不存在的数据,它需要该空数组将其绑定到data属性。

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

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