4
votes

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)?

1
What php framework are you using?samayo
@samayo custom PHP with some Symfony components.Stephan-v
so why don't you require the vue.js and only on those pages you want to include it?samayo
Because these pages also use other components, so they need access to Vue but they do not always need access to the router.Stephan-v
Do you have an PHP array of your php routes where you don't want vue route to work?samayo

1 Answers

7
votes

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.