Javascript 为什么这个去盎司函数会被破坏;这是什么;?
我创建了一个去盎司实用程序函数:Javascript 为什么这个去盎司函数会被破坏;这是什么;?,javascript,vue.js,vuejs2,Javascript,Vue.js,Vuejs2,我创建了一个去盎司实用程序函数: debounce (func, wait, immediate) { let timeout return function () { const context = this const args = arguments const later = function () { timeout = null if (!immediate) func.apply(context, args) }
debounce (func, wait, immediate) {
let timeout
return function () {
const context = this
const args = arguments
const later = function () {
timeout = null
if (!immediate) func.apply(context, args)
}
const callNow = immediate && !timeout
clearTimeout(timeout)
timeout = setTimeout(later, wait)
if (callNow) func.apply(context, args)
}
}
我是这样使用的:
updateField: utils.debounce((event, fieldName, schema) => {
const value = event.target.value
this.$emit('updateField', fieldName, value, schema)
validateFields(this)
}, 500),
去盎司功能有效。但是我得到了这个错误:
Uncaught TypeError: _this.$emit is not a function
有什么问题吗?假设
updateField
是一个Vue方法,因为它是用Vue标记的,这是因为您使用的是箭头函数
updateField: utils.debounce(function(event, fieldName, schema){
const value = event.target.value
this.$emit('updateField', fieldName, value, schema)
validateFields(this)
}, 500)
将其更改为常规函数
updateField: utils.debounce(function(event, fieldName, schema){
const value = event.target.value
this.$emit('updateField', fieldName, value, schema)
validateFields(this)
}, 500)
不应使用箭头函数定义Vue方法。原因是Vue将方法绑定到Vue,并且无法绑定箭头函数(您无法更改它们的this
)