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, 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的大坑
开发中只适用于调试! 不要用于线上环境,否则会有问题!
解决方案:
方案1.
const instance = getCurrentInstance()
console.log(instance.appContext.config.globalProperties)
获取挂载到全局中的方法
方案2.
const { proxy } = getCurrentInstance()
使用proxy线上也不会出现问题。
相关热词: vue3getCurrentIn使用
相关内容
这些是最新的
热门排行
- THINKPHP5+GatewayWorker+Workerman 开发在线客服系统
- 在手机浏览器网页中点击链接跳转到微信界面的方法
- 尊云网站目录系统 ThinkPHP5网站分类目录程序 v2.2.221011
- CentOS 7安装shadowsock(一键安装脚本)
- AdminTemplate 基于LayUI 2.4.5实现的网站后台管理模板
- 用NW.js(node-webkit)开发多平台的桌面客户端
- PHP生成随机昵称/用户名
- THINKPHP5网站分类目录程序 尊云网站目录系统
- 织梦(DEDECMS)微信支付接口 微信插件
- 基于LayUI开发的 网站后台管理模板 BeginnerAdmin
- 响应式后台网站模板 - AMA.ADMIN
- layuiAdmin后台管理模板 Iframe版
- LayUI 1.0.9 升级 至 LayUI 2.1.4 方法
- 简洁清爽的会员中心模板
- jQuery幸运大转盘抽奖活动代码