我正在构建一个小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 /数组更改做出反应......我很无能为力
答案 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
}
},