javascript 在Vue3钩子中,在返回类型对象内'this'总是'undefined'

z0qdvdin  于 2023-02-02  发布在  Java
关注(0)|答案(2)|浏览(259)

谁能告诉我,为什么在下面的代码中,在返回块中,this仍然是undefined

export const useAutoSave = (
  cacheKey: string,
  interval: number,
  getSaveData: () => Omit<SaveDto, 'savedTime'>,
) => {
  let timer: any
  const { storage, reset } = useStorageObject<SaveDto>(
    SaveDto,
    'auto-save-' + cacheKey,
    false,
  )
  const save = () => {
   // ...
  }
  return {
    reset,
    getPrevSaved() {
      return storage
    },
    save,
    track() {
      console.log(this) // <-- why is `this` `undefined` here?
      this.disposer() // <-- reference error
      timer = setInterval(save, interval)
    },
    disposer() {
      clearInterval(timer)
    },
  }
}
7hiiyaii

7hiiyaii1#

假设该函数位于模块this is automatically bound to undefined by Babel中,导致您观察到的错误。
要使代码正常工作,需要预先声明disposer(就像您对save()所做的那样):

export const useAutoSave = (
  cacheKey: string,
  interval: number,
  getSaveData: () => Omit<SaveDto, 'savedTime'>,
) => {
  let timer: any

  const disposer = () => {
    clearInterval(timer)
  }

  return {
    //...
    track() {
      disposer()
      timer = setInterval(save, interval)
    },
    disposer,
  }
}
sauutmhj

sauutmhj2#

请参考功能组件迁移指南和Vue 3功能组件文档。
您应该将propscontext作为参数传递给函数组件。

const FunctionalComponent = (props, context) => {
  // ...
}

相关问题