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 的方法注册全局变量。
<template>
<view class="body">
<uni-popup ref="popup" type="bottom">底部弹出 Popup</uni-popup>
</view>
</template>
import {
defineComponent,
onMounted,
getCurrentInstance,
ComponentInternalInstance,
} from "vue";
export default defineComponent ({
setup(){
const {
proxy, ctx } =
getCurrentInstance() as ComponentInternalInstance;
onMounted(() => {
ctx.$refs.popup.open();
});
return {
}
}
})