在vue3中获取this
<script setup>
import { getCurrentInstance } from "vue";// 获取当前实例,在当前实例充当vue2 中的this
// 获取当前组件实例
const instance = getCurrentInstance();
// 获取当前组件的上下文,下面两种方式都能获取到组件的上下文。
const { ctx } = getCurrentInstance(); // 方式一,这种方式只能在开发环境下使用,生产环境下的ctx将访问不到
const { proxy } = getCurrentInstance(); // 方式二,此方法在开发环境以及生产环境下都能放到组件上下文对象(推荐)
</script>
注意:该方法只能在函数外部获取,函数内部获取会报错,例如:
<script setup>
import { getCurrentInstance } from "vue";
const onSubmit = () => {
const { proxy } = getCurrentInstance();
proxy.$message.info("修改基本信息"); // 报错
};
</script>
解决:
<script setup>
import { getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance();
const onSubmit = () => {
proxy.$message.info("修改基本信息"); // 成功
};
</script>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。