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屋!