An alternative to this in Vue3

sequence:

Official explanation: inside setup(), this will not be a reference to the active instance (that is, not pointing to the vue instance), because setup() is called before parsing other component options, so the behavior of this inside setup() Completely different from this in other options. This can lead to confusion when using setup() with other options APIs. Therefore, this cannot be used in the setup function. So in order to avoid our wrong use, Vue directly changed this in the setup function to undefined)

I understand: in Vue3, setup is executed before the life cycle beforecreate and created, and the vue object has not been created at this time, so we cannot use the this we commonly use in vue2.x.

solution

The getCurrentInstance method in vue returns ctx and proxy. The console prints ctx and proxy and finds that it is equivalent to this in vue2.x. Friends who are used to using this can use proxy instead.

import {
    
    defineComponent, getCurrentInstance} from 'vue'

export default defineComponent ({
    
    
  setup(){
    
    
  
  	//vue3-typescript
    const {
    
     proxy, ctx } = (getCurrentInstance() as ComponentInternalInstance)
	//vue3-javascript
	const {
    
     proxy, ctx } = getCurrentInstance()
	
    const _this = ctx
    
    console.log('getCurrentInstance()中的ctx:', _this)
    console.log('getCurrentInstance()中的proxy:', proxy)
    
    return {
    
    }
  }
})

The project prints proxy under the development environment test
insert image description here

Note: ctx will become invalid after the vue3 project is packaged. You can also register global variables in App.vue with the method of provide + inject.

Guess you like

Origin blog.csdn.net/MoXinXueWEB/article/details/126938849