鍍金池/ 問答/HTML5  HTML/ vue+typescript項(xiàng)目中用this.$refs和原生方法獲取的dom有

vue+typescript項(xiàng)目中用this.$refs和原生方法獲取的dom有什么區(qū)別

項(xiàng)目中使用vue+typescript
使用this.$refs.refsName和document.querySelector打印出來的結(jié)果是一樣的

clipboard.png

但是當(dāng)使用API是。$refs獲得的DOM就報(bào)錯(cuò):請(qǐng)問是需要在ts項(xiàng)目中添加什么ts相關(guān)的配置嗎?

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 調(diào)用API正常
    console.log(window.getComputedStyle(element).width)
    console.log(element.getBoundingClientRect())
    
    // 2.el 調(diào)用報(bào)錯(cuò)
    // 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,定義一個(gè)類型

回答
編輯回答
扯機(jī)薄

this.$refs.refsName在類型定義上,并沒有g(shù)etBoundingClientRect的方法定義,所以你調(diào)用的時(shí)候會(huì)報(bào)類型錯(cuò)誤。
再比如我們項(xiàng)目中有人這樣定義:

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

然后我們動(dòng)態(tài)去options中添加屬性的時(shí)候:

ctrlLayout.options.id = "field1";

就會(huì)報(bào)同樣的錯(cuò)誤了,因?yàn)镺bject并沒有關(guān)于options.id的定義。
所以這個(gè)時(shí)候改成let ctrlLayout: any= undefined;就可以了。

2017年6月9日 15:26
編輯回答
離人歸

typescript 是強(qiáng)類型語言 你這屬于 類型不明確的問題

2018年3月21日 11:26