I have a simple VueJS app that I'm using with Firebase JSON database. I want to be able to click an arrow to update the "votes" of a comment. (similar to how this website has upvotes). My function runs. But the Vue Model never updates Firebase and so the vote count is lost on refresh. Please reference my CodePen: http://codepen.io/Auzy/pen/evowdd/ (Please note that I use Pug and Stylus, to see normal HTML/CSS click the arrow in top right.)
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
},
})
Alright, I believe I've figured it out. Please answer if you have a better method.
Here is the new method with added notes:
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
},