vue3中使用 getCurrentInstance

一、概念

         在 vue2 版本中,可以通过 this 来获取当前组件实例,但是在 vue3 setup 中是无法通过 this 获取组件实例对象,console.log(this) 打印出来的值是undefined。而使用 getCurrentInstance 方法就能获取当前组件的实例、上下文来操作 router 和 vuex 等。


二、使用

以 vant 组件为例点击确定按钮时隐藏弹出框,ref 标识当前组件 van-dropdown-item ,当点击确定按钮时通过 getCurrentInstance 来获取组件身上的属性方法,如: toggle()

<template>
   <van-dropdown-menu>
  <van-dropdown-item title="更多筛选" ref="sureScreen">
          此处代码省略............
          <div class="shiftBtn">
            <div class="defaultBtn btn">
              <van-button type="default" block round @click="resetMoreScreen">
                重置
              </van-button>
            </div>
            <div class="primaryBtn btn">
              <van-button type="primary" block round @click="onSureMoreScreen">
                确定
              </van-button>
            </div>
          </div>
        </van-dropdown-item>
</van-dropdown-menu>
</template>

<script setup>
import { getCurrentInstance, ref } from "vue";// 获取当前实例,在当前实例充当vue2 中的this
// 获取当前组件实例
const instance = getCurrentInstance();
// 获取当前组件的上下文,下面两种方式都能获取到组件的上下文。
const { ctx }  = getCurrentInstance();  //  方式一,这种方式只能在开发环境下使用,生产环境下的ctx将访问不到
const { proxy }  = getCurrentInstance();  //  方式二,此方法在开发环境以及生产环境下都能放到组件上下文对象(推荐)
// 确定更多筛选
const onSureMoreScreen = () => {
   // 隐藏更多筛选
  instance.proxy.$refs.sureScreen.toggle();
  //proxy.$refs.sureScreen.toggle();     //该方式作用和上面的一样
}
</script>

<style>
</style>

 三、注意事项

1、getCurrentInstance 只能在 setup 生命周期钩子中使用

2、ctx 和 proxy 都是 getCurrentInstance() 对象中的属性,通过解构赋值的方式拿到。可以看到,2者有所区别。ctx 是普通对象,proxy 是 Proxy 对象。

3、getCurrentInstance 是一个 function 方法,getCurrentInstance() 是一个对象,proxy 也是一个对象。proxy 是 getCurrentInstance() 对象中的一个属性,通过对象的解构赋值方式拿到 proxy。 

posted @ 2023-02-16 19:41  CodeFan*  阅读(1066)  评论(0编辑  收藏  举报