Laravel/Vue: SSR function not available in <script setup>

37 views Asked by At

It seems route() cannot be used in <script> and only in <template> when running Server-Side-Rendering.

So the question is: How to use the route() in the script when in SSR?

Steps to repreduce the error

1. Installation

Install new Laravel project

composer create-project laravel/laravel ssrtest

Go to the directory

cd ssrtest

Require laravel/breeze package

$ composer require laravel/breeze --dev

Install breeze using vue with ssr

php artisan breeze:install vue --ssr

2. Start server

Run server

php artisan serve

Open a new terminal/console in the same directory and start de node ssr command

php artisan inertia:start-ssr

Now you are running in SSR-mode where the routes are working .

You can now navigate to /login and back through the function route('login') in de Link-component in resources/js/Pages/Welcome.vue on line 37.

3. Creating the error

  1. First stop the ssr-node command. In the terminal Ctrl+C.

  2. Add the following link in de script-section of Welcome.vue

const testLink = route("login");
  1. Run the build again and start the ssr
npm run build && php artisan inertia:start-ssr
  1. Reload page in the browser

  2. See terminal for error

    Short version:

    [Vue warn]: Unhandled error during execution of setup function ...
    
    ReferenceError: route is not defined
    
1

There are 1 answers

0
Erik-Jan On

I think i found a solution.

It might not be the best...so...if someone has a better idea: i'm all ears.

import { Head, Link, usePage } from "@inertiajs/vue3";
import { useRoute } from "/vendor/tightenco/ziggy";

const route = useRoute(usePage().props.ziggy);
const testlink = route("login");

This way you can use route() in <script setup> and <template>