iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >vue3中getCurrentInstance示例讲解
  • 580
分享到

vue3中getCurrentInstance示例讲解

vue3 getcurrentInstancevue getcurrentInstance 2023-03-23 17:03:20 580人浏览 泡泡鱼
摘要

目录父组件中:main.js方式一、通过 getCurrentInstance 方法获取当前组件实例,从而获取 route 和 router方式二:通过从路由中导入 useRoute

父组件中:

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线上也不会出现问题

总结

到此这篇关于vue3中getCurrentInstance的文章就介绍到这了,更多相关vue3中getCurrentInstance内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: vue3中getCurrentInstance示例讲解

本文链接: https://www.lsjlt.com/news/201074.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作