头图

在vue3中获取this

<script setup>
import { getCurrentInstance } from "vue";// 获取当前实例,在当前实例充当vue2 中的this

// 获取当前组件实例
const instance = getCurrentInstance();

// 获取当前组件的上下文,下面两种方式都能获取到组件的上下文。
const { ctx }  = getCurrentInstance();  //  方式一,这种方式只能在开发环境下使用,生产环境下的ctx将访问不到
const { proxy }  = getCurrentInstance();  //  方式二,此方法在开发环境以及生产环境下都能放到组件上下文对象(推荐)

</script>

注意:该方法只能在函数外部获取,函数内部获取会报错,例如:

<script setup>
  import { getCurrentInstance } from "vue";
const onSubmit = () => {
  const { proxy } = getCurrentInstance();
  proxy.$message.info("修改基本信息"); // 报错
};
</script>

解决:

<script setup>
  import { getCurrentInstance } from "vue";
  const { proxy } = getCurrentInstance();

  const onSubmit = () => {
    proxy.$message.info("修改基本信息"); // 成功
  };
</script>

参考文章:
vue3中使用 getCurrentInstance


兔子先森
388 声望17 粉丝

致力于新技术的推广与优秀技术的普及。