vue3組件實列,上下文獲取問題

getCurrentInstance

獲取當前組件實例
import { getCurrentInstance } from "vue";
const instance = getCurrentInstance();

ctx

當前組件的上下文,只能在開發環境下使用,生產環境下的 ctx 將訪問不到,ctx 中包含了組件中由 ref 和 reactive 建立的響應式數據對象,以及 proxy 下的屬性
const { ctx } = getCurrentInstance();
  • 注意:在 setup 中不能夠調用 getCurrentInstance().ctx 來獲取組件內部數據,由於在 prod 模式會被幹掉
  • 緣由:vue

    • ctx 只是爲了便於在開發模式下經過控制檯檢查
    • 在 prod 模式是一個空對象

instance.ctx
圖片來源掘金 春去春又來react

proxy

在開發環境以及生產環境下都能放到組件上下文對象(推薦)

包含屬性$attrs,$data,$el,$emit,$forceUpdate,$nextTick,$options,$parent,$props,$refs,$root,$slots,$watchpost

const { proxy } = getCurrentInstance();
相關文章
相關標籤/搜索