Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally load vue-router

I am setting up my router on my main vue instance like so:

router.js:

const router = new VueRouter({
    routes: []
});

Main Vue instance:

import router from '@/router';

window.app = new Vue({
    el: '#vue',

    router,

    // etc.
});

Now I am running this inside a PHP application where this Vue instance is set up everywhere since I use Vue components all over the place.

The router is something I only use for a couple of pages though. There are only certain PHP pages I want to be able to have the Vue Javascript router.

Even on PHP pages where the router-view is not even loaded the router still activates. This is visible by the fragment:

#/

How would I make sure that the router only initiate on certain PHP routes(so to speak)?

like image 805
Stephan-v Avatar asked Mar 07 '23 10:03

Stephan-v


1 Answers

you can add global js variable to page. which will define that you need router or not. I assume that you can identify it by your php code.

so from php side you can write something like this based on condition true or flase;

// you can set this variable as per your need 
$needRouter = false;

then inside your html template

if its any template engine (for example we use twig) pass this variable in to template

<script>
    window.needRouter = {{ needRouter }};
</script>

or if you prefer to use core php

echo '<script>window.needRouter = ' . ($needRouter ? 'true' : 'false') . ';</script>';

this will out put <script>window.needRouter = true;</script> or <script>window.needRouter = false;</script> based on condition.

now inside your main.js

import router from '@/router';

let vueOptions = {
    el: '#vue', 
    // we will not assign route here
    // etc.
};

if(window.needRouter) {
    // we will assign route here if window.needRoute is true
    vueOptions.router = router;
}

window.app = new Vue(vueOptions);

if any confusion how you set js variable from php please comment.

like image 161
Hardik Satasiya Avatar answered Mar 15 '23 17:03

Hardik Satasiya