0👍
Update: Here is an example where I have mocked the firebase behavior. posts
should be a data
item, because you control its contents. computed
items are for derived values based on other data
or props
items. You wouldn’t make a computed
based on a value external to Vue, because such values are not reactive.
const payloads = [{
val() {
return {
key: 2,
up: 10,
down: 3
};
}
},
{
val() {
return {
key: 1,
up: 3,
down: 10
};
}
}
];
new Vue({
el: '#app',
components: {
postVoter: {
template: '#post-voter-template',
data() {
return {
posts: [{
key: 1,
up: 0,
down: 0
},
{
key: 2,
up: 1,
down: 0
},
{
key: 3,
up: 0,
down: 1
}
]
}
},
created() {
const i = setInterval(() => {
if (payloads.length) {
console.log("Doing");
const post = payloads.shift();
const item = this.posts.find((p) => p.key === post.val().key);
item.up = post.val().up;
item.down = post.val().down;
} else {
console.log("Done");
clearInterval(i);
}
}, 1000);
}
}
}
});
.container {
display: flex;
justify-content: space-between;
width: 10rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<template id="post-voter-template">
<div>
<div v-for="post in posts" class="container">
<p id="upvotes">{{ post.up}}</p>
<p id="downvotes">{{ post.down }}</p>
</div>
</div>
</template>
<post-voter id="app"></post-voter>
You should be finding which data item needs updated, rather than trying to find it in the DOM. You don’t say how posts
is created or populated, so I’m having to surmise what it looks like. The code should go something like this:
<template>
<div>
<div v-for="post in posts" class="container">
<p id="upvotes">{{ post.up}}</p>
<p id="downvotes">{{ post.down }}</p>
</div>
</div>
</template>
<script>
export default{
created() {
const ref = this.$firebase.database().ref();
ref.child("posts").on('child_changed', (post) => {
const item = this.posts.find((p) => p.key === post.key);
item.up = post.val().up;
item.down = post.val().down;
});
}
}
</script>
Source:stackexchange.com