Javascript Vue 3:使用此.$refs和lang=";ts";?
我一直在查看Vue 3+Typescript中$refs的文档,我被难住了 我读过各种博客文章,包括:Javascript Vue 3:使用此.$refs和lang=";ts";?,javascript,typescript,vue.js,vuejs3,Javascript,Typescript,Vue.js,Vuejs3,我一直在查看Vue 3+Typescript中$refs的文档,我被难住了 我读过各种博客文章,包括: ... setup() { const celestiaSkyViewerCanvas = ref(null) onMounted(() => { console.log(celestiaSkyViewerCanvas.value) }) return { celestiaSkyViewerCanvas
...
setup() {
const celestiaSkyViewerCanvas = ref(null)
onMounted(() => {
console.log(celestiaSkyViewerCanvas.value)
})
return {
celestiaSkyViewerCanvas
}
},
...
以及文件:
而且,好吧,我什么都试过了,我被难倒了
我有以下模板,其中有一个
元素,类型为htmlcanvaseElement
(我假设?),上面有一个“ref”:
。。。
设置(){
const celestiaSkyViewerCanvas=ref();
未安装(()=>{
console.log(celestiaSkyViewerCanvas.value)
})
返回{
celestiaSkyViewerCanvas
}
},
...
。。。
设置(){
const celestiaSkyViewerCanvas=ref();
未安装(()=>{
console.log(celestiaSkyViewerCanvas.value)
})
返回{
celestiaSkyViewerCanvas
}
},
...
什么都不管用。。。我要么在使用this.$refs
时出现typescript错误,要么就是没有定义
4个小时后我坐在这里,想知道,为什么从文档中很难理解这一点?HTML标记中的ref属性是
CelestiaSkyViewerCanvas
,您正在设置中定义CelestiaSkyViewerCanvas
ref。结合第一个和第二个示例以获得良好的类型支持。使用联合类型ref(null)初始化ref代码>。
...
setup() {
const celestiaSkyViewerCanvas = ref(null)
onMounted(() => {
console.log(celestiaSkyViewerCanvas.value)
})
return {
celestiaSkyViewerCanvas
}
},
...
...
setup() {
const celestiaSkyViewerCanvas = ref<HTMLCanvasElement>();
onMounted(() => {
console.log(celestiaSkyViewerCanvas.value)
})
return {
celestiaSkyViewerCanvas
}
},
...
...
setup() {
const celestiaSkyViewerCanvas = ref<ComponentPublicInstance<HTMLCanvasElement>>();
onMounted(() => {
console.log(celestiaSkyViewerCanvas.value)
})
return {
celestiaSkyViewerCanvas
}
},
...