Copyright © 2022-2025 aizws.net · 网站版本: v1.2.6·内部版本: v1.25.2·
页面加载耗时 0.00 毫秒·物理内存 138.6MB ·虚拟内存 1372.6MB
欢迎来到 AI 中文社区(简称 AI 中文社),这里是学习交流 AI 人工智能技术的中文社区。 为了更好的体验,本站推荐使用 Chrome 浏览器。
本文讲解"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>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)
}
})开发中只适用于调试! 不要用于线上环境,否则会有问题!
解决方案:
方案1.
const instance = getCurrentInstance() console.log(instance.appContext.config.globalProperties)
获取挂载到全局中的方法
方案2.
const { proxy } = getCurrentInstance()使用proxy线上也不会出现问题。
关于 "vue3中的getCurrentInstance怎么使用" 就介绍到此。希望多多支持编程教程。
vue3中怎么使用router路由实现跳转传参:本文讲解"vue3中如何使用router路由实现跳转传参",希望能够解决相关问题。 一、路由跳转1.首先在需要跳转的页面引入API—useRouterim ...