vue3中的getCurrentInstance如何使用
这篇“vue3中的getCurrentInstance如何使用”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“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, ponetInternalInstance,ref } from "vue"; import Child from "./zi.vue"; const child = ref(null) // as ponetInternalInstance表示类型断言,ts时使用。否则报错,proxy为null const { proxy } = getCurrentInstance() as ponetInternalInstance; 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 { definponent, getCurrentInstance } from 'vue' export default definponent({ name: 'About', setup(){ const { proxy } = getCurrentInstance() console.log(proxy.$root.$route) console.log(proxy.$root.$router) return {} } }) </script>
方式二:通过从路由中导入 useRoute useRouter 使用 route 和 router。
Html
import { definponent } from ‘vue' import { useRoute, useRouter } from ‘vue-router' export default definponent({ 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的大坑
开发中只适用于调试! 不要用于线上环境,否则会有问题!
解决方案:
方案1.
const instance = getCurrentInstance() console.log(instance.appContext.config.globalProperties)
获取挂载到全局中的方法
方案2.
const { proxy } = getCurrentInstance()
使用proxy线上也不会出现问题。
以上就是关于“vue3中的getCurrentInstance如何使用”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注测速网www.inhv.cn行业资讯频道。
下一篇:Vue3+Element-plus项目自动导入报错如何解决
南阳代办公司工商营业执照
南阳代办营业执照工商执照公司
南阳宛城区代办申请工商营业执照
南阳卧龙区代办工商营业执照
南阳个体户营业执照代办
南阳公司工商营业执照代办
南阳代办公司工商营业执照细节流
南阳代办营业执照需要的资料
唐山增值电信业务经营许可证申请
廊坊第二类增值电信业,ICP许可证