gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:35:49 25 4
gpt4 key购买 nike

我正在构建一个小型 vue.js 应用程序,我在其中执行一些发布请求。我使用 watch 方法来监视 api 更改,然后在发布请求成功时更新组件。由于观察者不断检查 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>

这给了我错误:无法读取未定义的属性“get”

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

编辑

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

updated(): {
this.fetchAll()
}

结果是请求在循环中运行:-/当我删除更新的生命周期时,组件(当然)不会对 api/数组更改使用react...我'我很无知

最佳答案

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

使用常规函数声明:

   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() watch 正在调用 this.fetchAll()。正如您所看到的,这会导致无限循环。

解决方案:通过从观察者中删除 fetchAll 调用来停止循环:

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

关于javascript - VueJS 如何在数据更改时使用 _.debounce,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49141504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com