setup 在生命周期 beforecreate 和 created 前执行,此时 vue 对象还未创建,因无法使用我们在 vue2.x 常用的 this。
解决办法是 vue 中的 getCurrentInstance 方法返回了 ctx 和 proxy,控制台打印 ctx 和 proxy 发现和 vue2.x 中的 this 等同,习惯使用 this 的同学可以用 proxy 进行替代。没有用 ctx 因为 vue3 项目打包后 ctx 会失效。也可以在 App.vue 用 provide + inject 的方法注册全局变量。
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