You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Inertia+Vue3提交新标签后如何在onSuccess获取数据更新Props?

Inertia + Vue3 提交新标签后获取数据并更新标签列表的解决方案

后端(Laravel)处理:返回新创建的标签数据

创建标签后,通过back()重定向回原页面,并用with()携带新标签数据。Laravel会将数据存入session flash,Inertia会自动把这些数据注入到前端的page.props.flash中。

修改后的后端代码:

$data = $request->validate([
    'name' => 'required|string|max:255',
]);

$tag = Tag::create($data);

// 重定向回原页面并携带新标签数据
return back()->with('newTag', $tag);

前端(Vue3)处理:在onSuccess中更新标签列表

在表单提交的onSuccess回调里,从返回的page对象中提取新标签数据,添加到本地维护的标签数组即可。同时注意文章表单的标题、描述用独立的本地ref/useForm维护,避免被重置。

修改后的前端代码:

defineProps({
    tags: {
        type: Array,
        required: true
    },
    styles: {
        type: Array,
        required: true
    },
})

// 用组件props初始化本地标签数组
const tags = ref([...props.tags]);
const styles = ref([...props.styles]);

// 文章表单用独立useForm维护,确保内容不被标签提交操作影响
const articleForm = useForm({
    title: '',
    description: '',
});

let addTag = () => {
    tagForm.post('/tags', {
        preserveScroll: true,
        resetOnSuccess: false,
        onSuccess: (page) => {
            // 提取后端传来的新标签
            const newTag = page.props.flash?.newTag;
            if (newTag) {
                // 将新标签加入本地标签数组
                tags.value.push(newTag);
            }
        },
    })
};

关键说明

  1. Inertia的useForm已经封装了AJAX逻辑,无需手动发送请求,表单提交后会自动处理响应。
  2. resetOnSuccess: false会阻止标签表单的字段被重置,文章表单的内容通过独立的useForm维护,不会受到标签提交操作的影响。
  3. 后端传递的flash数据仅在当前请求有效,避免了重复添加标签的问题,Inertia会自动清理这些临时数据。

内容的提问来源于stack exchange,提问作者Samet KAYA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 15:50:04