闲下来记录下之前刚接触Arco-design的坑——message方法在vue3中使用不了。
众所周知,如果在vue3里使用setup语法糖,就不能在里面使用this。因为setup执行时,组件对象还没有创建,所以this还是undefined,就自然不能用Arco官网的this.$message来调用。
继续往下找到官网给出的解决方案:
于是写出以下代码:
<template>
<a-button type="primary" @click="showMsg">点我弹出通知</a-button>
</template>
function showMsg() {
getCurrentInstance().appContext.config.globalProperties.$message.info('凉凉')
}
但是报错!appContext居然没有!
看来是getCurrentInstance()出了问题,于是打印:
<template>
<a-button type="primary" @click="showMsg">点我弹出通知</a-button>
</template>
function showMsg() {
console.log(getCurrentInstance())
getCurrentInstance().appContext.config.globalProperties.$message.info('凉凉')
}
果然是null!
这是再次想到了setup执行时机的问题,于是想到把getCurrentInstance()放到onMounted里,并且打印,终于看到了$message!!!!!:
onMounted(() => {
console.log(getCurrentInstance())
})
于是在setup里面,定义一个proxy变量,接收onMounted里的getCurrentInstance().proxy,达到在showMsg函数里调用的目的。
完整代码如下:
<script setup>
import { ref, getCurrentInstance, onMounted } from "vue";
let proxy = ref(null);
function showMsg() {
console.log(getCurrentInstance()); // null
proxy.value._.appContext.config.globalProperties.$message.success(
"聪明"
);
}
onMounted(() => {
proxy.value = getCurrentInstance().proxy;
console.log(proxy.value);
console.log(getCurrentInstance());
});
</script>
<template>
<a-button type="primary" @click="showMsg">点我弹出通知</a-button>
</template>
<style scoped></style>
成功!!!
码字不易,欢迎讨论。
有帮助的话点赞支持下哟~