Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/383.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Vue 3:使用此.$refs和lang=";ts";?_Javascript_Typescript_Vue.js_Vuejs3 - Fatal编程技术网

Javascript Vue 3:使用此.$refs和lang=";ts";?

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

我一直在查看Vue 3+Typescript中$refs的文档,我被难住了

我读过各种博客文章,包括:

  ...
  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
    }
  },
  ...