VueJS - How to update component data from a function inside a method?

允我心安 提交于 2021-02-05 06:40:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!