How to use this in Vue3 setup

In Vue2, the current component instance can be obtained through this; but in Vue3, the component instance cannot be obtained through this in the setup, and the value printed by console.log(this) is undefined.

So if you want to use this in Vue3 , Vue provides us with the getCurrentInstance() method, which returns ctx and proxy.

 1. Overview: a very important method to obtain the instance and context of the current component to operate router and vuex, etc.

2. Use: Provided by vue, this api cannot be found in the official documentation, and other alternatives can be found, which may not be recommended. . . Import on demand: import {  getCurrentInstance  } from 'vue'

import { getCurrentInstance } from 'vue';
// 获取当前组件实例
const instance = getCurrentInstance();
 
// 获取当前组件的上下文,下面两种方式都能获取到组件的上下文。
// 方式一,这种方式只能在开发环境下使用,生产环境下的ctx将访问不到
const { ctx }  = getCurrentInstance(); 
//  方式二,此方法在开发环境以及生产环境下都能放到组件上下文对象(推荐)
const { proxy }  = getCurrentInstance();  
// ctx 中包含了组件中由ref和reactive创建的响应式数据对象,以及以下对象及方法;

Both ctx and proxy are attributes in the getCurrentInstance() object, which are obtained by deconstructing and assigning. It can be seen that the two are different. ctx is an ordinary object, and proxy is a Proxy object.

Guess you like

Origin blog.csdn.net/qq_37485170/article/details/130267094