vue+typescript项目中用this.$refs和原生方法获取的dom有什么区别

项目中使用vue+typescript
使用this.$refs.refsName和document.querySelector打印出来的结果是一样的

clipboard.png

但是当使用API是。$refs获得的DOM就报错:请问是需要在ts项目中添加什么ts相关的配置吗?

Property 'getBoundingClientRect' does not exist on type 'Vue | Element | Vue[] | Element[]'.
  Property 'getBoundingClientRect' does not exist on type 'Vue'.
any
    let el = this.$refs.refsName
    console.log('el:', el);
    let element = document.querySelector('.content-box')
    console.log('element:', el);
    console.log(element['style'].width)
    // 1.element 调用API正常
    console.log(window.getComputedStyle(element).width)
    console.log(element.getBoundingClientRect())
    
    // 2.el 调用报错
    // Property 'getBoundingClientRect' does not exist on type 'Vue | Element | Vue[] | Element[]'.Property 'getBoundingClientRect' does not exist on type 'Vue'.any
    // console.log(el.getBoundingClientRect()) 
    // console.log(window.getComputedStyle(el).width)

知道了,要把let el = this.$refs.refsName改为:let el: any = this.$refs.refsName,定义一个类型

阅读 18.2k
3 个回答

typescript 是强类型语言 你这属于 类型不明确的问题

this.$refs.refsName在类型定义上,并没有getBoundingClientRect的方法定义,所以你调用的时候会报类型错误。
再比如我们项目中有人这样定义:

let ctrlLayout: Object= undefined;
ctrlLayout = {
   options: {}
}

然后我们动态去options中添加属性的时候:

ctrlLayout.options.id = "field1";

就会报同样的错误了,因为Object并没有关于options.id的定义。
所以这个时候改成let ctrlLayout: any= undefined;就可以了。

指定一下类型就可以了

let el = this.$refs.refsName as HTMLElement
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Microsoft
子站问答
访问
宣传栏