当我尝试更新firebase上的值时,我在数据列表上有一个非常奇怪的行为。
我在这里推出了一个代码示例: https://codepen.io/Raulmo/pen/BRMWNM?editors=1111
这是我的vueJS:
// Setup Firebase
let config = {
databaseURL: "https://test-stack-de2e3.firebaseio.com"
};
let firebaseapp = firebase.initializeApp(config);
let db = firebaseapp.database();
let postsRef = db.ref('blog/posts')
// create Vue app
var app = new Vue({
// element to mount to
el: '#app',
// initial data
data: {
posts: [],
newPost: {
title: '',
content: '',
story: ''
}
},
// methods
methods: {
addPost: function () {
postsRef.push(this.newPost);
this.newPost.title = '';
this.newPost.content = '';
this.newPost.story = '';
},
editPost: function(post) {
// Set post values to form
this.newPost = post
},
updatePost: function(post) {
post.title = "changed"
const childKey = post['.key'];
/*
* Firebase doesn't accept speacial chars as value
* so delete `.key` property from the post
*/
delete post['.key'];
/*
* Set the updated post value
*/
this.$firebaseRefs.posts.child(childKey).set(post)
},
removePost: function (post) {
postsRef.child(post['.key']).remove()
toastr.success('Business removed successfully')
},
},
// Explicitly set binding data to firebase as an array.
created() {
this.$bindAsArray('posts', postsRef);
}
})
每次按下编辑按钮时,我都强制将post.title的值更改为另一个值,然后在firebase上更新它,但是当我在第一个元素上执行此操作时,它也会更改列表的最后一个元素的值。所以,我需要重新加载页面以使其再次正确。
有人对导致它的原因有任何疑问吗?
答案 0 :(得分:0)
我也有同样的问题。但我认为这可以帮到你
它看起来很愚蠢,但它对我来说很有用
updatePost: function(post) { this.$firebaseRefs.posts.child(post['.key']).child('title').set(post.title)
this.$firebaseRefs.posts.child(post['.key']).child('content').set(post. content)
this.$firebaseRefs.posts.child(post['.key']).child('story').set(post. story)
},
答案 1 :(得分:0)
您必须使用帖子的副本
editPost: function(post) {
// Set post values to form
// create a copy of the post
this.newPost = {...post}
},