Vue3异步方法中调用SweetAlert2报$this.swal未定义如何解决
问题原因
Vue 3 的组合式API setup() 中不存在传统Options API的this组件上下文,你在main.js中全局挂载的$swal是绑定到组件实例上的属性,因此在setup()中直接访问this.$swal会触发未定义报错。
解决方案
以下两种方法都可以解决问题:
- 方法1:通过
getCurrentInstance获取全局挂载的$swal
修改Table.vue的script部分代码如下:
<script> import axios from 'axios' // 新增导入getCurrentInstance import { onMounted, ref, getCurrentInstance } from 'vue' export default { setup() { let transactions = ref([]) // 获取组件实例代理对象 const { proxy } = getCurrentInstance() || {} onMounted(() => { getTransactions() }) async function getTransactions() { try { let { data } = await axios.get('http://127.0.0.1:8000/api/transactions') transactions.value = data.data } catch(e) { // 用proxy访问全局挂载的方法,可选链避免空值报错 proxy?.$swal('Something went wrong.') } } return { transactions } } } </script>
- 方法2:直接引入SweetAlert2调用(更简洁,无需依赖全局挂载)
不需要使用全局注册的实例方法,直接在组件内导入SweetAlert2调用即可:
<script> import axios from 'axios' import { onMounted, ref } from 'vue' // 直接导入SweetAlert2 import Swal from 'sweetalert2' export default { setup() { let transactions = ref([]) onMounted(() => { getTransactions() }) async function getTransactions() { try { let { data } = await axios.get('http://127.0.0.1:8000/api/transactions') transactions.value = data.data } catch(e) { // 直接调用Swal.fire方法 Swal.fire('Something went wrong.') } } return { transactions } } } </script>
内容的提问来源于stack exchange,提问作者owf
相关产品推荐
相关产品推荐

