VueJS如何在数据更改时使用_.debounce

时间:2018-03-06 23:06:40

标签: javascript vue.js debounce

我正在构建一个小vue.js - 应用程序,我在那里发布一些帖子请求。我使用watch - 方法来进行api更改,然后在post请求成功时更新组件。由于观察者不断检查API我想添加._debounce方法但由于某种原因它不起作用。

这是代码:

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

这给了我错误Cannot read property 'get' of undefined

有人可以告诉我我做错了吗?

修改

我删除了watch - 方法并尝试添加

updated(): {
  this.fetchAll()
}

结果是请求在循环中运行: - /当我删除updated - 生命周期时,组件(当然)不会对api /数组更改做出反应......我很无能为力

1 个答案:

答案 0 :(得分:3)

请注意方法中的this() => {使this引用window而不是Vue实例。

使用常规function声明:

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

其他问题

你有一个循环依赖。

fetchAll方法正在改变cds属性(行this.cds = response.body),而cds()监视正在调用this.fetchAll()。如您所见,这会导致无限循环。

解决方案:通过从观察者处移除fetchAll来电来停止周期:

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