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.
Related
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>
Hello apologise for my question could be very dummy but i was not able to find correct answer in google. I dont have access to this.$router in Vue. From what i found it says vue inject router as dependecy to every component. But still my this.$route do not shows up. I'm using Vue version 3.2.1 and vue-router 3.0.1 (selected from CLI when project it's generated). Im alowed to navigate tho. Everything seems to be correctly just this dependency $router i dont have access to it.
I tryed to research in google everything but unsuccessfully. What i found it was only that which says vue inject router as dependency to every component still unsucesfull to find as property to my class $router. Everything else works good tho, i mean router link, router view just property to reach params or query or redirect is missing.
How did you initialize your vue-router module with Vue ?
It should be like this :
import Vue from 'vue'
import VueRouter from 'vue-router'
// Include plugin
Vue.use(VueRouter)
// Initialize your router
const vueRouter = new VueRouter({
routes: [] // your routes
})
// Send your router to your Vue top component
const app = new Vue({
el: '#my-app',
router: vueRouter,
render: h => h(App)
})
import Vue from 'vue';
import './plugins/vuetify'
import App from './App.vue';
import router from './router';
import store from './store';
import './registerServiceWorker';
Vue.config.productionTip = false;
new Vue({
router,
store,
render: h => h(App),
}).$mount('#app');
And i have separate file with my routes:
import Vue from 'vue';
import Router from 'vue-router';
import Home from './views/Home.vue';
import Signin from './views/Users/Signin.vue';
import Signup from './views/Users/Signup.vue';
import Profile from './views/Users/Profile.vue';
import AddPlace from './views/WorldPlaces/AddPlace.vue';
import AllPlaces from './views/WorldPlaces/AllPlaces.vue';
import DetailsPlace from './views/WorldPlaces/DetailsPlace.vue';
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: Home,
},
{
path: '/signup',
name: 'signup',
component: Signup
},
{
path: '/signin',
name: 'signin',
component: Signin
},
{
path: '/profile',
name: 'profile',
component: Profile
},
{
path: '/places/add',
name: 'addplace',
component: AddPlace
},
{
path: '/places/all',
name: 'allplaces',
component: AllPlaces
},
{
path: '/places/details/:id',
name: 'detailsplace',
component: DetailsPlace
}
// {
// path: '/about',
// name: 'about',
// // route level code-splitting
// // this generates a separate chunk (about.[hash].js) for this route
// // which is lazy-loaded when the route is visited.
// component: () => import(/* webpackChunkName: "about" */ './views/About.vue'),
// },
],
mode: 'history'
});
I have this vue js script
const NotfoundComponent = {
template: '<h1>Not found</h1>'
};
const HomeComponent = {
template: '<h1>Home</h1>'
};
const AboutComponent = {
template: '<h1>About</h1>'
};
const routes = [
{
path: '/',
component: HomeComponent
},
{
path: '/about',
component: AboutComponent
},
{
path: '*',
component: NotfoundComponent
}
];
const router = new VueRouter({
mode: 'history',
routes
});
new Vue({
el: '#app',
router
});
that uses vue-router. I am running vue js inside a jsp page inside a spring mvc app. I would like to have load the jsp page normally as served by jetty and only use vue js router to navigate between components inside the page.
I have the router setup and working inside the page, however on link click, i do not want any of this vue js links
<div id="app">
<router-link to="/">home</router-link>
<router-link to="/about">about</router-link>
<router-link to="/something">no route</router-link>
<router-view></router-view>
</div>
to modify the current address bar or append anything new to it.
Can that be done using vue js?.
You want 'abstract' mode.
const router = new VueRouter({
mode: 'abstract',
routes
});
This requires you push an initial URL:
// you main Vue instance
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App },
mounted() {
this.$router.replace('/') // added this
}
})
CodeSandbox demo here.
Please Check below link, you want to use abstract
https://jsfiddle.net/qpnaokhf/
const router = new VueRouter({
routes,
mode: 'abstract'
})
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.
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.