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的setup方法在beforecreate和created之前执行,无法直接使用this。通过getCurrentInstance可以获取到ctx和proxy,其中proxy与Vue2.x的this功能相似,适合用于替代this。需要注意的是,ctx在vue3项目打包后可能失效。另外,可以通过provide+inject在App.vue中注册全局变量作为替代方案。
最低0.47元/天 解锁文章
3176

被折叠的 条评论
为什么被折叠?



