關於Vue3里面的getCurrentInstance:可以獲取掛載在全局的屬性和獲取上下文
這里會碰到幾個問題:
一、不能使用getCurrentInstance的ctx
我們在獲取Vue3中全局掛載的方法時會這么寫:
這里的ctx不是setup提供的ctx
const { ctx } = getCurrentInstance()
這里ctx打包后在生產環境下是獲取不到的,請各位沒玩過生產的別不小心誤導到別人啊哈,恰好在Vue3的issues中找到的。
正確應該使用
const { proxy } = getCurrentInstance()
二、關於在ts中使用到類型定義錯誤問題
報錯:...類型“ComponentInternalInstance | null”
就嗝屁了。。。
1. 可以添加ts忽略去解決
// @ts-ignore const { proxy } = getCurrentInstance();
但是這個方法很無腦,也麻煩。。。
2. 考慮到在獲取上下文和全局掛載實例的時候會用到這個getCurrentInstance,那我們來新建 hooks\useCurrentInstance.ts
import { ComponentInternalInstance, getCurrentInstance } from 'vue' export default function useCurrentInstance() { const { appContext } = getCurrentInstance() as ComponentInternalInstance const globalProperties = appContext.config.globalProperties return { globalProperties } }
組件中使用
// 先引入文件 import useCurrentInstance from "@/hooks/useCurrentInstance"; ... // 在setup 中使用處理 const { globalProperties } = useCurrentInstance();
注意的點:千萬不要在getCurrentInstance() 中獲取ctx來使用element等東西,這玩意在生成環境下結構就不一樣了,會報undefined。可以使用proxy。(我第一次搞vue3就卡在這里2天)