[英]Property '$el' does not exist on type 'never'
I am working on a vue.js 3
project, where I need to refer/get a div
element in my script by initially declaring a null
reference like this const refRouterView = ref(null)
and I am not sure how to make TypeScript aware of DomElement
.我正在处理一个vue.js 3
项目,我需要通过最初声明null
引用来引用/获取脚本中的div
元素,就像这样const refRouterView = ref(null)
并且我不确定如何让 TypeScript 知道DomElement
。
<template lang="pug">
.flex
router-view(ref='refRouterView')
...
</template>
<script lang="ts" setup>
import { ref, onMounted } from 'vue';
const refRouterView = ref(null);
const routerViewHeight = ref(500);
const getRouterViewHeight = () => {
setTimeout(() => {
routerViewHeight.value = refRouterView.value?.$el.offsetHeight;
}, 250);
};
onMounted(() => getRouterViewHeight());
</script>
I was getting this error Object is possibly 'null'
before adding ?
我得到这个错误Object is possibly 'null'
before adding ?
to refRouterView.value?
到refRouterView.value?
which seems like hack and I don't like it.这看起来像黑客,我不喜欢它。 And, after adding ?
而且,添加后?
I started seeing this error Property '$el' does not exist on type 'never'.
我开始看到此错误Property '$el' does not exist on type 'never'.
I tried adding HTMLElement
to const refRouterView: HTMLElement = ref(null);
我尝试将HTMLElement
添加到const refRouterView: HTMLElement = ref(null);
but that introduce this error Property 'value' does not exist on type 'HTMLElement'.
但这会引入此错误Property 'value' does not exist on type 'HTMLElement'.
which was not solved even after adding ?
添加后还没有解决?
to refRouterView.value?
到refRouterView.value?
Please help!请帮忙!
Originally my question was using div(ref='refRouterView')
and @Thomas's answer solves it but I was using router-view
.最初我的问题是使用div(ref='refRouterView')
并且@Thomas 的回答解决了它,但我使用的是router-view
。 Just for making my question easy to understanding I mentioned div
instead of router-view
and that confused us, hence the answer did not solve my issue.只是为了让我的问题更容易理解,我提到了div
而不是router-view
,这让我们感到困惑,因此答案没有解决我的问题。
<template lang="pug">
.flex
div(ref='refRouterView')
...
</template>
If you ref
a DOM node, you don't have an $el
property, the ref directly points to the DOM node:如果你ref
一个 DOM 节点,你没有$el
属性,引用直接指向 DOM 节点:
https://v3.vuejs.org/guide/composition-api-template-refs.html https://v3.vuejs.org/guide/composition-api-template-refs.html
And for the typescript part, you have to define the type like this as the refRouterView
is a Proxy
of a certain type:对于 typescript 部分,您必须像这样定义类型,因为refRouterView
是某种类型的Proxy
:
const refRouterView = ref<HTMLDivElement>();
Then you can directly access the attributes:然后可以直接访问属性:
refRouterView.value.offsetHeight
(this.$refs.refRouterView as Vue & { $el: () => any }).$el.offsetHeight
Please refer to it: Vetur bug or code error?请参考: Vetur bug or code error? “property '$el' does not exist on type 'SVGelement' “‘SVGelement’类型上不存在属性‘$el’
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.