VueJS - 如何从方法内的函数更新组件数据? [英] VueJS - How to update component data from a function inside a method?
问题描述
我正在尝试使用 Firebase 进行搜索.我的 VueJS 代码中有这个.
I'm trying to do a search using Firebase. I have this in my VueJS Code.
export default {
data () {
return {
listings: [],
searchData: {
keyword: ""
}
}
},
name: 'SearchScreen',
components: {
ValidationProvider,
ValidationObserver
},
firebase: {
listings: listingsRef
},
methods: {
search () {
console.log(this.searchData.keyword)
listingsRef.orderByChild('location').equalTo(this.searchData.keyword).on('value', function (snapshot){
console.log(snapshot.val())
return{
listings: snapshot.val()
}
})
}
}
}
现在,当我执行 console.log
时,它成功地过滤掉了数据并在控制台中显示了响应.但是我无法使用从 Firebase 获得的响应更新组件数据中的列表".尝试了 this.listing
但没有奏效.我该怎么做?
Now when I do the console.log
It successfully filters out data and shows the response in the console. But I couldn't update the 'listings' in component data with the response I got from Firebase. Tried this.listing
but didn't work. How can I do this?
推荐答案
您应该将 this
(组件实例)分配给一个全局变量 vm
然后在回调中分配snapshot.val()
到 listing
数据属性如下:
You should assign this
(component instance) to a global variable vm
and then in the callback assign that snapshot.val()
to the listing
data property as follows :
search () {
console.log(this.searchData.keyword)
let vm =this;
listingsRef.orderByChild('location').equalTo(this.searchData.keyword).on('value', function (snapshot){
console.log(snapshot.val())
vm.listings= snapshot.val()
})
}
或将回调用作箭头函数 (snapshot)=>{}
:
or use the callback as an an arrow function (snapshot)=>{}
:
search () {
console.log(this.searchData.keyword)
listingsRef.orderByChild('location').equalTo(this.searchData.keyword).on('value', (snapshot)=>{
console.log(snapshot.val())
this.listings= snapshot.val()
})
}
这篇关于VueJS - 如何从方法内的函数更新组件数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!