简体   繁体   中英

Vue and Laravel SPA routes with params showing blank page on browser refresh and vue is not mounted on #app

I am using vue-router and Laravel for my applcation.

I have a url: http://mywebapp.com/post/ {id}

It works when i navigate normally by clicking the above link and vue router loads the component post.vue with route id as route parameter.

But when i refresh the page everything goes blank and vue is not mounted on

<div id="app"></div>

I don't think this is a server configuration issue because my .htaccess file is correctly configured and i don't get a 404 response.

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>


it just shows a blank page with no errors on the console so it's hard to trace the problem

The route
{
  path: "/post/:id",
  name: "Post",
  component: Post,
  meta: {
     requiresAuth: false
  }
}

The component
import Post from "./components/post/Post.vue";

when the component is loaded, it makes an Api request to fetch the post using the ID passed from the route

created() {
    this.loading = true;
    let url = `/post/${this.$route.params.id}`;

    axios.get(url).then(response => {
      this.loading = false;
      this.post = response.data.post;
    });
  }

Route on api.php

Route::get('/post/{id}', 'PostsController@show');

Controller

 public function show(Request $request, $id)
  {
    $post= Post::find($id);

    return response()->json([
      'post' => $clip
    ]);
  }

The above codes works normally as expected when i navigate to a post but i just got a blank screen when i reload the browser with no errors reported on the console.

How do i fix this?

Your web.php find should contain a route that matches all routes:

Route::get('/{any}', 'SpaController@index')->where('any', '.*');

This way Laravel doesn't interfere with vue router links.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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