简体   繁体   中英

VueJS how to use _.debounce on data changes

I'm building a little vue.js -application where I do some post requests. I use the watch -method to whach for api changes which then updates the component if the post request is successfull. Since the watcher constantly checks the API I want to add the ._debounce method but for some reason it doesn't work.

here is the code:

<script>
import _ from 'lodash'
export default { 
    data () {
      return {
        cds: [],
        cdCount: ''
     }
   },
   watch: {
     cds() {
       this.fetchAll()
     }
   },
   methods: {
      fetchAll: _.debounce(() => {
        this.$http.get('/api/cds')
         .then(response => {

          this.cds = response.body
          this.cdCount = response.body.length
         })
     })
  },
  created() {
     this.fetchAll();
  }
}
</script>

this gives me the error : Cannot read property 'get' of undefined

Can someone maybe tell me what I'm doing wrong?

EDIT

I removed the watch -method and tried to add

updated(): {
  this.fetchAll()
}

with the result that the request runs in a loop :-/ When I remove the updated -lifecycle, the component does (of course) not react to api/array changes... I'm pretty clueless

Mind the this : () => { in methods make the this reference window and not the Vue instance.

Declare using a regular function :

   methods: {
      fetchAll: _.debounce(function () {
        this.$http.get('/api/cds/add').then(response => {
          this.cds = response.body
          this.cdCount = response.body.length
         })
     })
   },

Other problems

You have a cyclic dependency.

The fetchAll method is mutating the cds property (line this.cds = response.body ) and the cds() watch is calling this.fetchAll() . As you can see, this leads to an infinite loop.

Solution: Stop the cycle by removing the fetchAll call from the watcher:

  watch: {
    cds() {
     // this.fetchAll() // remove this
    }
  },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM