10

在typeScript+vue项目中使用ref

 3 years ago
source link: https://segmentfault.com/a/1190000040233078
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

在typeScript+vue项目中使用ref

发布于 3 分钟前

因为vue项目是无法直接操作dom的,但是有时候开发需求迫使我们去操作dom。

两个办法,一个是很low的再引入jq,然后通过jq来操作,但是这样就失去了我们使用vue的意义
另一个就是添加ref属性,对ref进行操作。

好了完美解决。

很不巧,新项目用的是vue还是vue+typeScript的,直接,单纯的this.$refs.xxx不好用了,报错,识别不了,很尴尬。

经过不懈努力终于找到了在typeScript+vue项目中使用ref的解决办法:

添加一个声明类型,例如:
this.$refs.ceshiREF as HTMLAudioElement
这样是不报错了,但是打印的结果却是undefined,有点不讲道理的感觉。
后来在一片博客中发现ref不是响应式的,无法对添加了if的进行反应,而我不巧就添加在了有if判断的标签上面。
此外ref必须要数据渲染之后才能获取到,一般在mounted中。
而且也并不是像上面说的那样需要声明一个类型,而是需要声明一个变量:

let el:any = this.$refs.ceshi;
console.log(el)

这样就好了,我喜欢这样,因为非常简单我可以理解。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK