简体   繁体   中英

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

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.

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