sweetalert2:如何在重定向时拥有加载器动画
sweetalert2: How to have loader animation while redirecting
使用 sweetalert2@8 模式对话框。
目标是当用户在对话框中单击“确定”时重定向到 URL。然后,当重定向发生时,sweet_alert 必须尽可能长时间保持打开状态,同时显示加载动画。
尝试了以下方法:
swal.fire({
title: "my title",
type: "warning",
html: "my body text",
showCancelButton: true,
showLoaderOnConfirm: true,
closeOnConfirm: false,
}).then((result) => {
if(result.value)
{
window.location.href = "/target_location/"
}
})
结果:重定向有效,但按下“确定”按钮后对话框立即消失。
我们如何让它可见并显示加载器动画?
两个参数将有助于处理这种情况:showLoaderOnConfirm
和 preConfirm
。
showLoaderOnConfirm
Set to true to disable buttons and show that something is loading. Use it in combination with the preConfirm parameter.
preConfirm
Function to execute before confirm, may be async (Promise-returning) or sync
因为你想要永不停止的“无限”加载器(浏览器重新加载将更新页面),你需要returnpreConfirm()
中的never-resolving承诺:
Swal.fire({
showLoaderOnConfirm: true,
preConfirm: function (value) {
location.assign('https://google.com')
return new Promise( resolve => {} ) // never-resolving promise
},
})
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
使用 sweetalert2@8 模式对话框。
目标是当用户在对话框中单击“确定”时重定向到 URL。然后,当重定向发生时,sweet_alert 必须尽可能长时间保持打开状态,同时显示加载动画。
尝试了以下方法:
swal.fire({
title: "my title",
type: "warning",
html: "my body text",
showCancelButton: true,
showLoaderOnConfirm: true,
closeOnConfirm: false,
}).then((result) => {
if(result.value)
{
window.location.href = "/target_location/"
}
})
结果:重定向有效,但按下“确定”按钮后对话框立即消失。
我们如何让它可见并显示加载器动画?
两个参数将有助于处理这种情况:showLoaderOnConfirm
和 preConfirm
。
showLoaderOnConfirm
Set to true to disable buttons and show that something is loading. Use it in combination with the preConfirm parameter.
preConfirm
Function to execute before confirm, may be async (Promise-returning) or sync
因为你想要永不停止的“无限”加载器(浏览器重新加载将更新页面),你需要returnpreConfirm()
中的never-resolving承诺:
Swal.fire({
showLoaderOnConfirm: true,
preConfirm: function (value) {
location.assign('https://google.com')
return new Promise( resolve => {} ) // never-resolving promise
},
})
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>