【问题标题】:calling SweetAlert2 inside Async method in VUE 3在 VUE 3 的 Async 方法中调用 SweetAlert2
【发布时间】:2021-07-20 09:07:30
【问题描述】:

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

我在 main.js 中导入了甜蜜警报:

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>

任何建议如何解决这个问题?

【问题讨论】:

    标签: vue.js vuejs3 sweetalert2


    【解决方案1】:

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

    vue-sweetalert2 通过app.config.globalProperties.$swalprovide-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

    当使用“Vue3: Composition API”时,最好不要使用这个包装器。直接调用sweetalert2比较实用。

    你可以像这样直接使用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

    【讨论】:

      【解决方案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 !')
          }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2020-07-01
        • 2022-08-09
        • 1970-01-01
        • 1970-01-01
        • 2022-06-30
        • 2023-01-28
        • 1970-01-01
        • 2021-03-29
        • 1970-01-01
        相关资源
        最近更新 更多