序:
官方解说: 在 setup() 内部,this 不会是该活跃实例的引用(即不指向vue实例),因为 setup() 是在解析其它组件选项之前被调用的,所以 setup() 内部的 this 的行为与其它选项中的 this 完全不同。这在和其它选项式 API 一起使用 setup() 时可能会导致混淆。因此setup函数中不能使用this。所以Vue为了避免我们错误的使用,直接将setup函数中的this修改成了 undefined)
我理解: 在Vue3中,setup 在生命周期 beforecreate 和 created 前执行,此时 vue 对象还未创建,因此,无法使用我们在 vue2.x 常用的 this。
解决方案
vue 中的 getCurrentInstance 方法返回了 ctx 和 proxy,控制台打印 ctx 和 proxy 发现和 vue2.x 中的 this 等同,习惯使用 this 的朋友可以用 proxy 进行替代。
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 {}
}
})
项目在开发环境测试下打印 proxy
注意: ctx 会因为 vue3 项目打包后失效,这里还可以在 App.vue 用 provide + inject 的方法注册全局变量。