vue3 typescript 在methods和setup中使用$refs并解决Object is possibly “null”

在vue中,通常在template中给某组件设置了 ref属性后,在methods中,直接this.$refs调用即可。

但是使用了typescript后,this.$refs.xxx将会被提示Object is of type 'unknown'。这需要将变量定义一下类型。

import  XXComponent  from 'XXComponent.vue';
...
(this.$refs.xxx as XXComponent).method
import { XXComponent } from 'XXComponent';
...
(this.$refs.xxx as typeof XXComponent).method

然后在setup中是没有this使用的,官方文档中写到使用的例子

<template>
  <div ref="root">This is a root element</div>
</template>
<script>
  import { ref, onMounted } from 'vue'
  export default {
    setup() {
      const root = ref(null)
      onMounted(() => {
        // the DOM element will be assigned to the ref after initial render
        console.log(root.value) // <div>This is a root element</div>
      })
      return {
        root
      }
    }
  }
</script>

然而,直接复制官方的例子后,在setup中想使用组件的方法,root.value.xxx提示Object is possibly ‘null’。methods中使用setup导出的root.xxx也提示Object is possibly ‘null’。需要定义一下这个root的类型

import {onMounted} from 'vue';
...
interface IComponent{
    xxx?:Function
}
...
setup(){
const root = ref<IComponent>({});
onMounted(() => {
            console.log(root.value.xxx) 
        //执行
        root.value.xxx(params);
        
      })
},
methods:{
    YYY(){
        console.log(root.xxx);
        //执行
        root.xxx(params);
    }
}

只在methods中使用就是对每个$refs的属性对象都需要转换类型判断,如果是组件就需要import组件。

在setup中定义共享出去就需要定义每一个使用到的ref。

参考文章:
https://www.lanwuyaojiu.cn/blogm/blogart-112.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值