Ionic 使用vuews $refs中的focus()和离子组件时,对象的类型为“未知”

exdqitrt  于 2022-12-08  发布在  Ionic
关注(0)|答案(1)|浏览(145)

我正在使用离子框架与vueJs TS。
我尝试通过编程方式将焦点设置在<ion-input>上,

<ion-input
              ref="todoItemLabel"
              placeholder="Task name"
              v-model="label"></ion-input>

我在控制器中用来聚焦的代码是

this.$refs.todoItemLabel.$el.focus()

问题是编译器给予我下一个错误:

Object is of type 'unknown'

原因是什么?我该如何克服这个问题?

vhmi4jdf

vhmi4jdf1#

I struggled to find a solution for a long time, so I hope others will find this answer helpful.
The problem lies within Typescript validation.
We need to define the object type in order to use it.
So for using the refs object properties we need to tell TS what is this type of object.
The solution was:

(this.$refs.todoItemLabel as InstanceType<typeof IonInput>).$el.focus()

so instead of directly trying to access .$el we set the property type first so Typescript will know how to use it and what properties to expect from it.
if you have the same problem with other Ionic elements, you just need to set them here: i.e.

(this.$refs.todoItemLabel as InstanceType<typeof IONIC_COMPONENT_NAME>).$el.THE_ELEMENT_METHOD_TO_CALL()

I hope it will save other people time :-)

相关问题