Laravel Vue VueRouter history mode

Viewed 2952

I'm building an e-commerce project with laravel, vue and vue router

I want to use vue router with history mode but it cause me trouble.

Here is my code

new Vue({
    el: '#app',
    router: new VueRouter({
        mode: 'history',
        routes
    })
});

Here is my route in web.php which have locale middleware

Route::group(['prefix' => '{locale}', 'where' => ['locale' => '[a-zA-Z]{2}'], 'middleware' => 'setlocale'], function () {
    Route::view('/{path?}', ('layouts.app'))->where('path', '.*');
});

Here is my route with vue router

export const routes = [
    {
        path: '/',
        component: require('./components/Page/HomePage').default,
    },
    {
        path: '/product',
        component: require('./components/Page/Product/ProductPage').default,
    },
];

I need my url to be

http://localhost/en

instead of (with the hashtag)

http://localhost/en#/

After using history mode, i successfully remove the hashtag. But, the router link of other will remove my locale in my url

http://localhost/product

I don't know what to do now with it. Please help~ Thanks.

Update 19 Mar 2020 enter image description here

2 Answers

You need to set the base value to tell Vue Router what the base URL of your application is. In your case you can set it dynamically using the locale value.

For example, in your Blade template you could have the following script to set the locale value on the JavaScript window object:

<script>
    window._locale = "{{ app()->getLocale() }}";
</script> 

And then you can set the base value to the locale when creating your router:

router: new VueRouter({
  mode: 'history',
  base: `/${window._locale}/`,
  routes
})

Very simple way is too Accept the locale in Vue router too. So your route would be like this:

export const routes = [
    {
        path: '/:locale',
        children: [
        {
            path: '',
            component: require('./components/Page/HomePage').default,
        },
        {
            path: 'product',
            component: require('./components/Page/Product/ProductPage').default,
        },
        ]
    }
];

just be sure for children route dont put '/' in begining because its remove locale

Related