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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With