简体   繁体   English

对惯性响应和 json 响应 Laravel Jetstream 使用相同的方法

[英]Use same method for inertia response and json response Laravel Jetstream

I have been using Laravel powered API and VueJS powered frontend, two separate projects for single page application.我一直在使用 Laravel 驱动的 API 和 VueJS 驱动的前端,这两个单独的项目用于单页应用程序。 Now I want to switch to Laravel Jetstream with Inertia.js as I can create SPA in a single project.现在我想使用 Inertia.js 切换到 Laravel Jetstream,因为我可以在单个项目中创建 SPA。 Here is an example how inertia works-这是惯性如何工作的示例-

class UsersController extends Controller

{
    public function index()
    {
        $users = User::active()
            ->orderByName()
            ->get(['id', 'name', 'email']);

        return Inertia::render('Users', [
            'users' => $users
        ]);
    }
}

Now we can define Route::get('users',['UserController::class','index']);现在我们可以定义Route::get('users',['UserController::class','index']); and get user list going to localhost:8000/users and see the user list in the web page.并获取用户列表到localhost:8000/users并在 web 页面中查看用户列表。

My question is, can I use the same controller and method for API response to use in Mobile App?我的问题是,我可以在移动应用程序中使用相同的 controller 和 API 响应方法吗?

I have to build web application and mobile application with same features.我必须构建具有相同功能的 web 应用程序和移动应用程序。 For web, I need inertia response and for mobile app, I need json response.对于 web,我需要惯性响应,对于移动应用程序,我需要 json 响应。 For showing the user list in Laravel project, I can use the code above.为了显示 Laravel 项目中的用户列表,我可以使用上面的代码。 But how do I return the same response as JSON like return response($users);但是我如何返回与 JSON 相同的响应,如return response($users); for mobile application?用于移动应用程序? I can create API routes in api.php and make separate controller or method or add condition for API or Inertia response, but I think there might be a better way to handle both Inertia and JSON response using same controller and method.我可以在api.php中创建 API 路由并单独创建 controller 或方法或为 API 或惯性响应添加条件,但我认为可能有更好的方法来处理惯性和 881569932 使用 same408584 方法和响应

Yes, you can totally do that by checking wether or not request wants a json response.是的,您完全可以通过检查请求是否需要 json 响应来做到这一点。 Something like this:像这样的东西:

public function index()
{
    $users = User::active()
        ->orderByName()
        ->get(['id', 'name', 'email']);

    if (request()->wantsJson()) {
        return $users;
    }

    return Inertia::render('Users', [
        'users' => $users
    ]);
}

Being honest here, partial reloads doesn't always cut it.老实说,部分重新加载并不总是能解决问题。 The reason I'm not a big fan is because most things I personally work with are Promise based.我不是忠实粉丝的原因是因为我个人使用的大多数东西都是基于Promise的。 With partial reloads , you would be using a callback.使用部分重新加载,您将使用回调。 I'll show both ways you can do it since recently this has piqued my interest.我将展示两种方法,因为最近这激起了我的兴趣。

If you want to go about doing it yourself via axios for example:例如,如果您想通过 axios 自己动手 go:

<script>
import { usePage } from '@inertiajs/inertia-vue3';

const { version } = usePage();

export default {
    name: 'Users',
    props: {
        users: Object,
    },
    data() {
        return {
            userObj: [],
            loading: false,
        };
    },
    methods: {
        customReload() {
            this.loading = true;

            this.axios.get('/users', {
                headers: {
                    'X-Inertia': true,
                    'X-Inertia-Partial-Component': 'Users',
                    'X-Inertia-Partial-Data': 'users',
                    'X-Inertia-Version': version.value,
                }
            }).then(({data}) => {
                console.log(data.props.users);
                this.userObj = data.props.users;
            })
            .catch(console.error)
            .then(() => {
                this.loading = false;
            });
        },
    },
};
</script>

Read more about this titled The protocol in the inertia docs that explain the header data used and what it's for.阅读更多关于惯性文档中标题为“协议”的信息,该文档解释了所使用的 header 数据及其用途。

Pros优点

  • Access ANY inertia render endpoint and get it's props访问任何惯性渲染端点并获取它的道具
  • You can access the data and manipulate it however you like您可以随心所欲地访问和操作数据
  • Props are untainted(if you'd like to reference to a previous version)道具未受污染(如果您想参考以前的版本)

Cons缺点

  • Does not update props不更新道具
  • Adds more code complexity增加了更多的代码复杂性
  • Storing multiple objects isn't the best use of ram存储多个对象并不是 ram 的最佳用途

Now this other approach, we can look into partial reloads .现在这种另一种方法,我们可以研究部分重新加载 You can call a partial reload by calling this.$inertia.reload({ only: ['PROP_NAME_HERE'] }) , but this isn't all the parameters you can insert.您可以通过调用this.$inertia.reload({ only: ['PROP_NAME_HERE'] })来调用partial reload ,但这并不是您可以插入的所有参数。

<script>
export default {
    name: 'Users',
    props: {
        users: Object,
    },
    data() {
        return {
            loading: false,
        };
    },
    methods: {
        partialReload() {
            this.loading = true;
            this.$inertia.reload({
                only: ['users'],
                onSuccess() {
                    // Print new props!
                    console.log(this.users);
                },
                onBefore(PendingVisit) {},
                onError(Errors) {},
                onStart() {},
                onProgress() {},
                onComplete() {},
                onAbort() {},
                onCancel() {},
                onFinish(ActiveVisit) {
                    this.loading = false;
                },
            });
        },
    },
};
</script>

Pros优点

  • Refresh data in props as per documentation根据文档刷新 props 中的数据
  • Less memory overhead减去 memory 开销

Con缺点

  • (bias)Callbacks (偏向)回调

I do certainly see a point where both of these can be used.我确实看到了可以同时使用这两种方法的观点。 Storing the data you get from your custom axios call, may not be necessary, you could be using it for a small object prop.存储您从自定义 axios 调用中获得的数据,可能不是必需的,您可以将它用于一个小的 object 道具。 But point is, the option is yours!但重点是,选择权在你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM