vue3中getCurrentInstance示例講解
父組件中:
1.setup語法糖中導入子組件
2.在子組件標簽上綁定ref值
3.setup內部從vue中按需導出 getCurrentInstance 方法
4.調用getCurrentInstance方法導出proxy
5.通過proxy.$refs.子組件ref名.子組件內屬性/方法 實現調用
<template> <!-- 父組件 --> <div> <!-- 子組件 --> <Child ref="child" /> <button @click="changeChildren">子組件count+1</button> </div> </template> <script setup lang="ts" name="Father"> import { getCurrentInstance, ComponetInternalInstance,ref } from "vue"; import Child from "./zi.vue"; const child = ref(null) // as ComponetInternalInstance表示類型斷言,ts時使用。否則報錯,proxy為null const { proxy } = getCurrentInstance() as ComponetInternalInstance; function changeChildren() { proxy.$refs.child.count += 1; //也可以使用ref數據.value的形式調用: //child.value.count += 1 console.log(child.value.name) } </script> <style scoped></style>
main.js
import api from "./utils/api.js" import StringUtil from "./utils/StringUtil.js" app.config.globalProperties.api = api; app.config.globalProperties.StringUtil = StringUtil;
import {getCurrentInstance } from 'vue'; const { proxy } = getCurrentInstance(); console.log(proxy.api); console.log(proxy.StringUtil.isBlank('1'));
方式一、通過 getCurrentInstance 方法獲取當前組件實例,從而獲取 route 和 router
Html
<template> <div> </div> </template> <script> import { defineComponent, getCurrentInstance } from 'vue' export default defineComponent({ name: 'About', setup(){ const { proxy } = getCurrentInstance() console.log(proxy.$root.$route) console.log(proxy.$root.$router) return {} } }) </script>
方式二:通過從路由中導入 useRoute useRouter 使用 route 和 router。
Html
import { defineComponent } from ‘vue' import { useRoute, useRouter } from ‘vue-router' export default defineComponent({ setup () { const $route = useRoute() const r o u t e r = u s e R o u t e r ( ) c o n s o l e . l o g ( router = useRouter() console.log(router=useRouter()console.log(route) console.log($router) } })
附:Vue3中關于getCurrentInstance的大坑
開發(fā)中只適用于調試! 不要用于線上環(huán)境,否則會有問題!
解決方案:
方案1.
const instance = getCurrentInstance() console.log(instance.appContext.config.globalProperties)
獲取掛載到全局中的方法
方案2.
const { proxy } = getCurrentInstance()
使用proxy線上也不會出現問題
總結
到此這篇關于vue3中getCurrentInstance的文章就介紹到這了,更多相關vue3中getCurrentInstance內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Element-ui DatePicker顯示周數的方法示例
這篇文章主要介紹了Element-ui DatePicker顯示周數的方法示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-07-07Vue3+Vite 環(huán)境變量和模式配置詳解(推薦)
在Vue 3中,你可以通過 import.meta.env 訪問環(huán)境變量,這些變量可以在你的應用代碼中使用,但它們通常用于配置不應該硬編碼在代碼中的值,這篇文章主要介紹了Vue3+Vite 環(huán)境變量和模式配置詳解,需要的朋友可以參考下2024-12-12