在用vant组件库的Toast组件,需要用到实例。vue2中用的this,但vue3中没有this。而是用getCurrentInstance 来获得实例。参考了这位博主的写法,但是却报错了。如下图:
用了两种方法解决这个问题:
法一:安装volar
(推荐)
这位博主的写法是没有问题的,vue3需要安装一个插件,vscode中搜索volar,第一个就是。安装之后就不报错了。
法二:
import { getCurrentInstance,ref } from "vue"
const currentInstance = getCurrentInstance()
const proxy = ref(currentInstance?.proxy)
//调用toast
proxy.value?.$toast({})