vuejs how to get get all routes after add router dynamiclly - vue.js

New to vuejs, so there is a constant router object
const constantRouterMap = [{
a,b,c }]
and imported to Router object
new Router({
mode: 'history',
...
......
routes: constantRouterMap
})
And I have also added routers in a js file
import router from '#/router'
.......
.....
router.addRoutes(dynamicRouters)
Then I tried to get all routes with
router.options.routes
or
getRoutes()
But this only gives me 3 routes from constantRouterMap .
How can I get all routes included the routes I created dynamically ?

Are you sure you're calling getRoutes() after you added the additional routes? Are you getting any errors? Are any of the the new routes overwriting existing routes?
Working code:
const router = new VueRouter({
routes: [
{
path: '/foo',
component: { template: '<div/>' }
}
]
})
router.addRoute({
path: '/bar',
component: { template: '<div/>' }
})
// Log the paths of each route
console.log(router.getRoutes().map(r => r.path))
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

Related

Vue routing dynamic

I have a backoffice in Laravel with dynamic routes, however, I don't know how I do this in vue js, that is, create routes dynamically, so that a controller or something like that returns me the correct view!
You could try Vue Router's Dynamic Route matching, passing different values for route parameters: https://router.vuejs.org/guide/essentials/dynamic-matching.html
Small example for you.
Laravel part
Your "web" routes in Laravel
Route::get('/{any}', 'AppController')->where('any', '.*');
Inside invoke controller
public function __invoke()
{
return view('app');
}
In app.blade
#extends('layouts.app')
#section('content')
<div id="app">
<app/>
</div>
#endsection
Vuejs part:
Your router file
import Login from "./views/Login";
import Home from "./views/Home";
import NotFound from "./views/NotFound";
Vue.use(VueRouter);
let router = new VueRouter({
routes: [
{ path: '/login', name: 'login', component: Login },
{ path: "/", name: 'home', component: Home },
{ path: "*", name: '404', component: NotFound }
});
In app.js
import router from './router';
const app = new Vue({
store,
router,
i18n,
el: '#app',
});
All post, put, patch routes should be "api" routes.

Remove Hashbang on VueJs with Laravel

I have already tried the suggestions stated regarding the hashbang (/#/) with Vue and Laravel, and it seems it still doesn't work for me.
routes.js
let routes = [
{
path: '/',
component: Home,
children: [
{
path: '/blog',
component: PageBlogLists,
},
{
path: '/post/:page_id',
component: PageBlog
}
]
},
];
export default new VueRouter({
// This does not work
mode: 'history',
routes
});
app.js
// Vue Router
import VueRouter from 'vue-router';
import router from './router/routes';
require('./bootstrap');
window.Vue = require('vue');
Vue.use(VueRouter);
const app = new Vue({
el: '#app',
router
});
Has anyone successfully tried removing it?

Cannot read query params becouse vue.js is adding #/ to the end of url

I have a one page app in vueJS:
let router = new VueRouter({
routes: [
{ path: '/', component: Dis13HomeComponent },
{ path: '**', component: Dis13HomeComponent }
]
});
In main component in mounted() im getting the url param like this:
this.$route.query.token;
But if I open http://www.myapp.com/app.html?token=s56ds6d5d56f6ef6e it does not read the token parameter, becouse vue is adding #/ to the end of url so it looks like http://www.myapp.com/app.html?token=s56ds6d5d56f6ef6e#/
If I open this format of url: http://www.myapp.com/app.html#/?token=s56ds6d5d56f6ef6e then it works, but this path is forbidden on server.
How could I read the token parameter?
Make your router to work with history mode and you will not have the '#' anymore.
const router = new VueRouter({
mode: 'history', // <------------- HERE
routes: [
{ path: '/', component: Dis13HomeComponent },
{ path: '**', component: Dis13HomeComponent }
]
});

How do I link the route to the component using vue-router?

I'm trying to use vue-router to link url's to their corresponding components.
My issue is that only the root url ('/') can link to the correct component and any other url (e.g. '/first') does not link to their component. All of them link to the component which belongs to the '/' url.
When I use "a" tag in the vue file it will route to the right component - it's only when I input the url directly into the browser that it doesn't work
main.js:
import Vue from 'vue'
import router from './router/index.js'
Vue.use(ElementUI)
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
// components: { App },
render: h => h(App)
})
index.js:
import Vue from 'vue'
import Router from 'vue-router'
import Hello from '../components/Hello.vue'
import First from '../components/firstPage.vue'
import Login from '../components/logIn.vue'
Vue.use(Router)
const routes =[
{
path: '/',
component: Login
},
{
path:'/first',
component:Hello
}
]
const router = new Router({
routes
})
export default router
I think you can also try as below. It's works, just try it! You can add mode: 'hash', to give default # in all urls.
import Vue from 'vue';
import Router from 'vue-router'
import Hello from '../components/Hello.vue'
import First from '../components/firstPage.vue'
import Login from '../components/logIn.vue'
Vue.use(VueRouter);
const router = new VueRouter({
mode: 'hash',
base: '/your_base_name_if_you_want',
linkActiveClass: 'active-tab', //if you w
routes: [
{
path: '/',
redirect: '/if_you_want_to_redirect',
name: 'Login', //Whatever
component: {
render (c) { return c('router-view'); }
},
children: [
{
path: '/',
component: Login
name: 'Login',
meta: { title: 'Your title name' }
},
{
path:'/first',
component:Hello
name: 'Hello',
meta: { title: 'Your title name' }
}
]
}
]
})
export default router
You can also remove it from your urls using:
var router = new VueRouter({
history: true
});
Hope this helps you!
The default mode for vue-router is hash mode
This is why you can't get the 'Hello' component when your url is '/first'. Instead you can try input '/#/first'.
If you want to use history mode like '/first', set the mode attribute for your route object like this.
const router = new Router({
mode: 'history',
routes
})
Hope it helps you.

vue-router 2, how to fetch routes via ajax?

How do I create the routes array dynamically, after fetching it via ajax?
Is there a way to add/push new routes to the router after it has been initialized?
This doesn't work:
new Vue({
el: '#app',
template: '<App/>',
data: {
content: []
},
created: function () {
this.$http.get('dummyjsondatafornow').then((response) => {
// this doesn't work when creating the VueRouter() outside the Vue instance, as in the docs.
// this.$router.options.routes.push({ path: '/about', component: About })
let routes = [
{ path: '/about', component: About }
]
// this doesn't work either
this.router = new VueRouter({
routes: routes
})
})
},
// router: router,
components: { App }
})
I don't believe there is no.
That said you can wildcard the route so that may provide you with an alternative.
I built a site where the backend (and in turn pages created) were controlled via a CMS which served all pages to Vue as JSON. This meant Vue wasn't aware of the routes the backend was creating.
Instead we passed all the CMS pages to Vue Router via a single * wildcard component. In Vue Router 2 this would look like:
const routes = [
{ path: '*', component: AllPages }
]
Vue Router 2 allows for Advanced Matching Patterns
These allow you to set a wide variety of conditions, therefore whilst you can't inject the object passed back via ajax into your router you can add a dynamic component to an AllPages component that is wildcard matched. This would allow you to pass the name of the component to load via your ajax request and then load that component when the page is called. i.e.
Your Ajax response:
{
// url: component name
'/about/': 'about',
'/about/contact/': 'contact',
...
}
Then in an AllPages vue component:
<template>
<component v-bind:is="currentView"></component>
</template>
<script>
module.exports = {
data () {
return {
currentView: '',
ajaxRoutes: {}, // loaded via ajax GET request
...
}
},
// watch $route to detect page requests
watch: {
'$route' (to, from) {
if (this.ajaxRoutes[to]) {
this.currentView = this.ajaxRoutes[to]
}
}
},
...
}
</script>
The above is a rather abbreviated idea but essentially you dynamically load the component based on the path the user requested.
I think this is fixed in version 2.3.0. You can now run
router.addRoutes(routes);
to dynamically add routes.
https://github.com/vuejs/vue-router/commit/0e0fac91ab9809254174d95c14592e8dc2e84d33
I have the same situation wherein my routes are built on the backend as it is maintained thru a CMS. With that, I was able to retrieve my routes thru an API call then return it on the vue router. Here's my take:
routes.js
const router = store.dispatch('cms/fetchRoutes').then((response) => {
const router = new VueRouter({
routes: response,
mode: 'history',
...
});
...
return router;
});
export default router;
main.js
import router from './router';
....
router.then((router) => {
const app = new Vue({
router,
store,
render: (h) => h(App),
}).$mount('#app')
...
});
Basically I do an axios call to fetch my routes then inject the response to the VueRouter routes property. Then on the main.js, do another then and inject the return on the Vue.
By then, my menus are now being retrieved from the database. No more hard coded paths.