Javascript VueJS如何在数据更改时使用u.debounce
我正在构建一个小的Javascript VueJS如何在数据更改时使用u.debounce,javascript,vue.js,debounce,Javascript,Vue.js,Debounce,我正在构建一个小的vue.js-应用程序,在这里我可以执行一些post请求。我使用watch-方法来检查api更改,如果post请求成功,则会更新组件。由于观察者不断检查API,我想添加\u debounce方法,但由于某些原因,它不起作用 代码如下: <script> import _ from 'lodash' export default { data () { return { cds: [], cdCount: ''
vue.js
-应用程序,在这里我可以执行一些post请求。我使用watch
-方法来检查api更改,如果post请求成功,则会更新组件。由于观察者不断检查API,我想添加\u 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>
结果是请求在一个循环中运行:-/当我删除
更新的
-生命周期时,组件(当然)不会对api/数组更改做出反应。。。我非常无知注意方法中的this
:()=>{
使this
引用窗口而不是Vue实例
使用常规的函数声明
:
methods: {
fetchAll: _.debounce(function () {
this.$http.get('/api/cds/add').then(response => {
this.cds = response.body
this.cdCount = response.body.length
})
})
},
其他问题
你有一个循环依赖
fetchAll
方法正在变异cds
属性(linethis.cds=response.body
),而cds()
watch正在调用this.fetchAll()
。如您所见,这会导致无限循环
解决方案:通过从观察者删除fetchAll
调用停止循环:
watch: {
cds() {
// this.fetchAll() // remove this
}
},
注意方法中的this
:()=>{
使this
引用窗口而不是Vue实例
使用常规的函数声明
:
methods: {
fetchAll: _.debounce(function () {
this.$http.get('/api/cds/add').then(response => {
this.cds = response.body
this.cdCount = response.body.length
})
})
},
其他问题
你有一个循环依赖
fetchAll
方法正在变异cds
属性(linethis.cds=response.body
),而cds()
watch正在调用this.fetchAll()
。如您所见,这会导致无限循环
解决方案:通过从观察者删除fetchAll
调用停止循环:
watch: {
cds() {
// this.fetchAll() // remove this
}
},
嗯,由于某种原因,我现在没有得到任何数据!?:-/仍然是同一个问题:-你是什么意思?提出了请求,但是cd
和cdCount
没有更新?我得到了一个空列表,请求甚至没有得到执行是的,但仍然不起作用。请随时检查我更新的问题嗯,出于某种原因,我没有得到任何数据ta现在!?:-/仍然是同一个问题:-你是什么意思?提出了请求,但未更新CD
和cdCount
?我得到了一个空列表,请求甚至没有得到执行是的,但仍然不起作用。请随时检查我更新的问题