[英]Inertia: Reload page with updated data without modifying scroll position
I'm using Inertia/Laravel/VueJs.我正在使用 Inertia/Laravel/VueJs。 I have a page with many posts and each post can be marked as completed.
我有一个包含许多帖子的页面,每个帖子都可以标记为已完成。 When a post is marked as completed on the front-end I have a v-bind which toggles a CSS class which should be applied to completed tasks.
当一个帖子在前端被标记为完成时,我有一个 v-bind 来切换一个 CSS 类,该类应该应用于已完成的任务。
The behaviour I would like is: a user scrolls down a page, clicks the completed button, and the back-end sends that newly updated data to the front-end, making the v-bind true, causing the CSS class to be applied without jumping to the top of the page.我想要的行为是:用户向下滚动页面,单击完成的按钮,后端将新更新的数据发送到前端,使 v-bind 为真,导致应用 CSS 类而无需跳转到页面顶部。
With the code below I can click the completed button, and it is updated in the database, but that new data isn't sent to the front-end.使用下面的代码,我可以单击完成的按钮,它会在数据库中更新,但新数据不会发送到前端。
Controller:控制器:
public function markAsCompleted(Request $request)
{
$post = Post::find($request->id);
$post->completed = true;
$post->save();
return Redirect::route('posts');
}
Javascript function called at click of completed button:单击完成按钮时调用的 Javascript 函数:
completed(id) {
this.completedForm.put(`/endpoint/completed/${id}`, {
preserveScroll: true
});
},
If I change the Javascript function to:如果我将 Javascript 函数更改为:
completed(id) {
this.completedForm.put(`/endpoint/completed/${id}`, {
preserveScroll: true,
onSuccess: () => {
Inertia.get('posts');
},
});
},
In this case, the new data is returned to the front-end with the post being marked as completed, but the preserveScroll doesn't work, and jumps the user to the top of the page.在这种情况下,新数据返回到前端,帖子被标记为完成,但preserveScroll不起作用,并且将用户跳转到页面顶部。
Any ideas on how to get my desired use case working?关于如何让我想要的用例工作的任何想法? Users could have hundreds of posts so I can't have the page jump up to the top every time.
用户可能有数百个帖子,所以我不能每次都让页面跳到顶部。
Thank you for any help!感谢您的任何帮助!
One way, not the cleanest, but it is a solution.一种方式,不是最干净的,但它是一种解决方案。 Just click "Completed Button" to send a request to the backend, and ONLY to check if the response is success, then update that task in frontend as complete.
只需单击“完成按钮”向后端发送请求,仅检查响应是否成功,然后在前端更新该任务为完成。 So you just update (add class) this element and you don't rerender whole DOM.
因此,您只需更新(添加类)此元素,而无需重新渲染整个 DOM。 Because, if you get success response, thats done in the backend for sure.
因为,如果您得到成功响应,那肯定是在后端完成的。
To update your app while preserving the state:要在保留状态的同时更新您的应用程序:
Inertia.get('posts', params, {
preserveState: true,
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.