问题
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()
}
})
}
}
}
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?
回答1:
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()
})
}
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()
})
}
回答2:
One way to do that is to bind this
to your function:
listingsRef.orderByChild('location').equalTo(this.searchData.keyword).on('value', function (snapshot){
this.listings = snapshot.val()
}.bind(this))
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
回答3:
to the search function add a reference to the component
thisComponent = this
then inside the function (snapshot)
use thisComponent.searchData.keyword = (whatever)
来源:https://stackoverflow.com/questions/61324085/vuejs-how-to-update-component-data-from-a-function-inside-a-method