在 VUE 3 的异步方法中调用 SweetAlert2

calling SweetAlert2 inside Async method in VUE 3

如果无法从服务器检索数据,我尝试弹出 sweetalert

我在 main.js 中导入了 sweet alert :

import VueSweetalert2 from 'vue-sweetalert2'
import 'sweetalert2/dist/sweetalert2.min.css'

const app = createApp(App)
app.use(VueSweetalert2)
app.mount('#app')

在 Table.vue 组件中,我尝试调用 swal 但出现错误提示 (undefined $this.swal) :

<script>
import axios from 'axios'
import { onMounted, ref } from 'vue'

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) {
                this.$swal('Something went wrong.')
            }
        }

        return {
            transactions
        } 

    }
}
</script>

有什么解决办法的建议吗?

您不能使用this 作为setup() 中的组件实例,因为组件尚未创建。还有其他方法可以获得 $swal 属性.

vue-sweetalert2 通过 app.config.globalProperties.$swal or as a provide-ed $swal prop.

公开 SweetAlert

在 Composition API 中使用它的一种简单方法是通过 inject():

import { inject } from 'vue'

export default {
    setup() {
        const swal = inject('$swal')

        async function getTransactions() {
            //...
            swal('Something went wrong.')
        }
    }
}

demo 1

但是,vue-sweetalert2 文档建议在这种情况下直接使用 sweetalert2

When using "Vue3: Composition API" it is better not to use this wrapper. It is more practical to call sweetalert2 directly.

你可以像这样直接使用sweetalert2

import { onMounted, inject } from 'vue'
import Swal from 'sweetalert2'

export default {
  name: 'App',
  setup() {
    async function getTransactions() {
      //...
      Swal.fire('Something went wrong.')
    }

    onMounted(() => getTransactions())
  }
}

demo 2

main.js文件中

import VueSweetalert2 from 'vue-sweetalert2';
import 'sweetalert2/dist/sweetalert2.min.css';

const app = createApp(App);

app.use(VueSweetalert2);
window.Swal =  app.config.globalProperties.$swal;
app.mount("#app");

在 COMPOSITION API

中使用 Swal.fire()
export default {
  setup() {
    function yourFunctionName() {
      Swal.fire('Hello !')
    }
  }
}