Laravel vue inertia show sweetalert message on form success

yvfmudvl  于 7个月前  发布在  其他
关注(0)|答案(2)|浏览(49)

所以我在我的主布局文件中包含了这个组件,它看起来像这样:

<script setup>
import {usePage} from "@inertiajs/vue3";
import {computed} from "vue";

const page = usePage()
const message = computed(() => page.props.flash.message)

if (message) {
  Swal.fire({
    text: 'Success!',
    icon: 'success',
    toast: true,
    showConfirmButton: false,
    position: 'bottom',
    timer: 3500
  });
}
</script>

字符串
上面是我一直在玩的东西.现在它显示的flash消息,甚至提交任何形式之前立即.我想只显示在一个成功的表单提交.我认为最好的事情是只包括一次成功的表单提交后的组件.但由于消息总是立即显示我一直在尝试与上述没有成功到目前为止.
从我的控制器,我重定向回一个flash消息,如下所示:

return redirect()->route('user.dashboard')->withMessage('It works');


在我的HandleInertiaRequests中间件中,我添加了:

return array_merge(parent::share($request), [
    'flash' => [
        'message' => session('message')
    ]
]);


我知道我可以像这样在div中显示消息,这是有效的:

<div v-if="$page.props.flash.message">{{ $page.props.flash.message }}</div>


但这不是我想要的,我想显示sweetalert消息,并且只显示一次。

mwngjboj

mwngjboj1#

在您app.blade.php文件中添加以下内容

<!-- sweetalert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

字符串
HandleInertiaRequests.php中添加以下内容

public function share(Request $request): array
{
    return array_merge(parent::share($request), [
    //add this
        'flash' => [
            'status'=> session('status')
        ]
    ]);
}


然后创建Swal.vue

<template></template>
<script setup>
import { onMounted, onUpdated } from 'vue';
const props = defineProps({
    status: {
        type: Object,
        default: {}
    },
});

function showSwal() {
    Swal.fire(
        props.status.action,
        props.status.text,
        props.status.type
    )
}

onMounted(() => {
    if (props.status) {
        showSwal()
    }
})

onUpdated(() => {
    if (props.status) {
        showSwal()
    }
})
</script>


然后将其添加到布局文件中

<Swal v-if="$page?.props.flash?.status" :status="$page?.props.flash?.status" />


最后要用它就用这个

return back()->with('status', ['type' => 'success', 'action' => 'type of acction', 'text' => 'your text here']);

clj7thdc

clj7thdc2#

如果我理解正确的话,你想显示一次警报。这意味着只有当组件被安装时,SweetAlert才会弹出。

<script setup>
import { usePage } from "@inertiajs/vue3";
import { onMounted, computed } from "vue";

const page = usePage();
const message = computed(() => page.props.flash.message);

onMounted(() => {
  if (message.value) {
    Swal.fire({
      text: message.value,
      icon: 'success',
      toast: true,
      showConfirmButton: false,
      position: 'bottom',
      timer: 3500
    });
  }
});
</script>

字符串
但是,您应该在显示SweetAlert后清除 Flink 消息。

相关问题