typescript - 如何修复错误 TS2339 - 'HTMLElement' 上不存在属性

标签 typescript vue.js vuejs3 typescript-generics

当我按下“下一步”按钮时,会触发下面的代码,执行所需的操作(如果需要,滚动到我的元素)。

但是出现此错误:错误TS2339:“HTMLElement”类型上不存在属性“scrollIntoViewIfNeeded”。并且我无法构建我的项目。

const h3Title = ref<HTMLElement | null>(null)
function nextStep(
  currentStep.value++;
  
  if (h3Title.value) {
    h3Title.value.scrollIntoViewIfNeeded({behavior: "smooth", block: "start"})
  }

最佳答案

我认为 h3Title.value.scrollIntoView({block: "nearest"}) 使用标准的scrollIntoView属性可以实现你想要的(如果元素已经在 View 中则不滚动)。

如果您确实希望 typescript 识别非标准的scrollIntoViewIfNeeded属性,您可以将其添加到HTMLElement接口(interface)(或创建扩展HTMLElement的新接口(interface)):

// global.d.ts
interface HTMLElement {
  scrollIntoViewIfNeeded?: any;
}

或者:将 h3Title.value 转换为 any 类型

(h3Title.value as any).scrollIntoViewIfNeeded()

关于typescript - 如何修复错误 TS2339 - 'HTMLElement' 上不存在属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74407151/

相关文章:

typescript - 如何在应用程序模型中使用 FieldValue.serverTimestamp

javascript - Vue 3 数据不可回溯

javascript - 如何在 VueJS 3 中使用 9.0.1 Firebase 方法

vue.js - Vue 3 通过双向绑定(bind)将 react 对象传递给组件

webpack - 在 Vue.JS SPA 中添加包的正确方法

javascript - 自定义事件是否会在 Vue 3 中向上传播组件链?

javascript - Angular 2使用动态键从json数组中获取键和值

javascript - 根据另一个单词数组对单词数组进行排序

javascript - 遍历 Angular 2 中的嵌套 FormArray

jquery - VueJS Accordion Table——基于实时系统的约束