RVN-3L
RVN-3L

Reputation: 1

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. 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. 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:

<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:

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 = '';
    }
  }
});

Upvotes: 0

Views: 1408

Answers (1)

Sepshun
Sepshun

Reputation: 21

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.

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.

Upvotes: 1

Related Questions