如何在Vue+Inertia表单中实现preserve-scroll功能
解决Inertia.js中表单提交/update方法无法保留滚动位置的问题
你遇到的情况是:在Vue结合Inertia的项目里,用Link组件实现删除功能时preserve-scroll属性能正常保留滚动位置,但通过表单提交或div的change事件触发update方法调用form.put时,滚动位置无法保留。
你的代码示例:
<template> <form @submit.prevent="update"> <div @change="update"> <input v-model="form.description" type="text" /> <input v-model="form.amount" type="text" > <select v-model="form.frequency"> <option>Weekly</option> <option>Monthly</option> <option>Quarterly</option> <option>Yearly</option> </select> <Link :href="`/budget/${props.budget.id}`" method="DELETE" as="button" preserve-scroll>  Delete</Link> </div> </form> </template> <script setup> import { useForm } from '@inertiajs/vue3' import { Link } from '@inertiajs/vue3' const props = defineProps({ budget: Object, }) const form = useForm({ id: props.budget.id, description: props.budget.description, amount: props.budget.amount, frequency: props.budget.frequency, }) const update = () => { form.put(`/budget/${props.budget.id}`); } </script>
解决方案
直接在form.put方法的第二个参数中传入preserveScroll: true配置即可,修改后的update方法如下:
const update = () => { form.put(`/budget/${props.budget.id}`, { preserveScroll: true }); }
原理说明
Link组件的preserve-scroll属性会自动将这个配置传递给Inertia的底层请求,但useForm提供的put/post/patch等提交方法,默认不会携带preserveScroll配置,必须手动指定这个参数才能触发滚动位置保留的行为。
如果是直接使用Inertia的全局方法(比如Inertia.put),同样可以在第三个参数中添加该配置:
import { Inertia } from '@inertiajs/vue3' // 示例调用 Inertia.put(`/budget/${props.budget.id}`, form.data(), { preserveScroll: true })
内容的提问来源于stack exchange,提问作者Marianne Hartigan
相关产品推荐
相关产品推荐

