2017-04-05 82 views
0

我有一個簡單的VueJS應用程序,與Firebase JSON數據庫一起使用。我希望能夠點擊箭頭來更新評論的「投票」。 (類似於這個網站的upvotes)。我的功能運行。但Vue模型從不更新Firebase,因此刷新時投票計數會丟失。請參考我的CodePen:http://codepen.io/Auzy/pen/evowdd/(請注意,我用哈巴狗和手寫筆,看到普通的HTML/CSS點擊右上方的箭頭。)Vue JS將增加的數字保存到Firebase數據庫

JS:

// Initialize Firebase 
var config = { 
    databaseURL: "..." 
}; 
const firebaseapp = firebase.initializeApp(config); 
const db = firebaseapp.database(); 
const commentsRef = db.ref('test'); 

const app = new Vue({ 
    el: '#app', 
    data: { 
     comments: [], 
     newComment: { 
      name: '', 
      comment: '', 
      votes: 0 
     }, 
    }, 
    methods: { 
     addComment() { 
      commentsRef.push(this.newComment); 
      this.newComment.name = ''; 
      this.newComment.message = ''; 
      this.newComment.votes = 0; 
     }, 
     vote: function (voteType, comment) { 
      if (voteType === "up") { 
       comment.votes++ 
      } else if (voteType === "down") { 
       if (comment.votes <= -10) { 
        return; 
       } 

       comment.votes--; 
      } 
     }, 
    }, 
    firebase: { 
     comments: commentsRef 
    }, 

}) 
+0

的'firebase'屬性不是一個標準的'Vue'選項。你在使用[vuefire](https://github.com/vuejs/vuefire)嗎?如果是這樣,它在哪裏? – Phil

+0

是的,我正在使用VueFire。腳本標籤位於我的CodePen JS設置下的資源。 – Auzy

回答

1

好吧,我相信我已經弄清楚了。請回答如果你有更好的方法。

下面是新方法與添加註釋:

incrementVote(comment) { 
    comment.votes++ //increment the vote count 
    const businesschildKey = comment['.key']; //get key of modified comment 
    delete comment['.key']; //Firebase doesn't know how to handle them but can use VueFire to get around that. 
    this.$firebaseRefs.comments.child(businesschildKey).set(comment) //Updates Firebase record matching key 
},