Home > Article > Web Front-end > How to use getCurrentInstance in vue3
1. Import the sub-component in setup syntax sugar
2. Bind the ref value on the sub-component label
3. Setup internally from Export the getCurrentInstance method on demand in vue
4. Call the getCurrentInstance method to export proxy
5. Implement the call through proxy.$refs.subcomponent ref name.properties/methods in the subcomponent
<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>
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'));
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>
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) } })
It is only suitable for debugging during development! Do not use it in an online environment, otherwise there will be problems!
Solution:
Option 1.
const instance = getCurrentInstance() console.log(instance.appContext.config.globalProperties)
Get the method of mounting to the global
Option 2.
const { proxy } = getCurrentInstance()
Use There will be no problems with proxy online.
The above is the detailed content of How to use getCurrentInstance in vue3. For more information, please follow other related articles on the PHP Chinese website!