No Route name in VueJS 3 + VueRouter 4 - vue.js

I am using VueJS 3 and Vue Router 4. I want to get the name of the current route using {{$route.name}} - this works so far. But it doesn't return any Route Name, if I'm accessing a route - in this Example I am trying to access /plans/1 - it doesn't return any value. here is my routes-array from the router:
const routes = [
{
path: '/plans',
name: 'Learning Plans',
component: ListPlans
},
{
path: '/plans/:id',
name: "Leaning Plan: Learn",
component: ViewPlan,
props: true
},
{
path: '/plans/:id/edit',
name: "Edit Learningplan",
component: EditPlan,
props: true
}
]
What am I doing wrong?
Thanks for every help!

Vue Router 4.x provides useRoute() for that:
import { useRoute } from 'vue-router'
export default {
setup() {
const route = useRoute()
onMounted(() => {
const id = route.params.id
})
}
}
DEMO

Related

Vue 3 router: props and query not working on beforeEach navigation guard

Using Vue 3 / Vue Router 4: I'm trying to implement a login screen that redirects to the requested deep link after login. But any prop or query I add to the navigation guard (so I can pass the requested URL to the login component) isn't visible to the login component. Here's the relevant code:
// Router
import { createRouter, createWebHistory } from "vue-router";
import Login from "#/views/Login.vue";
import Header from "#/components/Header.vue";
const routes = [
{
path: "/",
name: "Login",
components: {
default: Login,
Header: Header,
},
props: {
Header: { showMenu: false },
},
meta: { requiresAuth: false },
},
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
});
router.beforeEach((to) => {
if (to.meta.requiresAuth && !router.app.user.isAuthenticated()) {
return { name: "Login", props: { default: { target: to.name } } };
}
});
// Login.vue
<script>
export default {
name: "Login",
props: {
target: {
type: String,
default: "Home",
},
},
</script>
The target property remains at the default value no matter which named route I try to request. Nor does passing the value through the query string appear to work. I'm able to pass properties to components in the route definitions themselves without incident, it's just the navigation guard function that causes problems. What am I missing?
I might be missing something but the code you posted throws errors for me and the way you handle the navigation guard seems a bit strange (you should always have at least one next() in the guard).
Anyway, if I understand correctly and if you insist on using the same route for Header and Login pages, you could do this in your SFC and remove the guard from router file:
// App.vue
<template>
<router-view :name="page" />
</template>
<script>
export default {
data() {
return {
user: null
}
},
computed: {
page() {
if (this.$route.meta.requiresAuth && !this.user?.isAuthenticated()) {
return 'Login'
}
return undefined
}
}
created() {
this.user = <your_method_to_get_user>
}
}
</script>
// Router
import { createRouter, createWebHistory } from "vue-router";
import Login from "#/views/Login.vue";
import Header from "#/components/Header.vue";
const routes = [
{
path: "/",
name: "Login",
components: {
default: Login,
Header: Header,
},
props: {
Header: { showMenu: false }, // showMenu prop will beaccessible in Header
},
meta: { requiresAuth: false },
},
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
});
But I'd suggest using 2 different routes for login and header and redirecting from header to login if user not logged in and vice versa via the next() as described here.

Process 404 page when there is no parameter in Vue

Dynamic routing is in use.
If there is no device data in vuex, I want to go to 404 page.
How should I implement it?
router/index.js
const routes = [
{
path: '/',
name: 'Main',
component: Main
},
{
path: '/:device',
name: 'Detail',
component: Detail,
},
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
component: NotFound
},
]
When the device-detail page is implemented as follows, it does not move to the 404 page.
const deviceName = route.params.device
const storedDeviceList = computed(() => store.state.stationName)
if (!storedDeviceList.value.includes(deviceName)) {
router.push({
name: 'NotFound'
})
}
I think the first problem is, that you declare router two times in your project, according to your github repo. You declared your routes in your router/index.js and imported it into your main.js. So importing it again in About.vue from vue-router instead of router.js causes, that this instance has no routes. The second problem is the same with your store, as you import store/index.js to your main.js but import a new instance from vuex to your About.vue.
If you would use the composition API, you could call the already in main.js imported modules with this, like:
this.$router.push({
name: 'NotFound'
})
You also would get your states from your store like this:
this.$store.state.stationName
So, in composition API, use something like this in your About.vue:
<script>
export default {
methods: {
checkDevice() {
if (!this.$store.state.deviceList.includes(this.$route.params.device)) {
this.$router.push({
name: 'NotFound'
})
}
}
},
created() {
this.checkDevice()
}
}
</script>

How to add router with query param to router list?

I want to add a route with query params.
If the url is blog, then navigate to index page.
If the url includes the author query param, replace a component on the page with the BlogAuthorPage component.
router: {
extendsRoutes(routes, resolve) {
routes.push({
name: 'author-page-detail',
path: '/blog?author=*',
component: resolve(__dirname, 'pages/blog/author-page.vue')
})
}
}
This should not be done in nuxt.config.js's router key but rather in your blog.vue page directly with a component router guard.
The code below should be enough to check if the route does have a author query params and redirect to the blog/author-page page.
<script>
export default {
beforeRouteEnter(to, from, next) {
next((vm) => {
if (vm.$route.query?.author) next({ name: 'blog-author-page' })
else next()
})
},
}
</script>
I use "#nuxtjs/router": "^1.6.1",
nuxt.config.js
/*
** #nuxtjs/router module config
*/
routerModule: {
keepDefaultRouter: true,
parsePages: true
}
router.js
import Vue from 'vue'
import Router from 'vue-router'
import BlogIndexPage from '~/pages/blog/index'
import BlogAuthorPage from '~/pages/blog/author-page';
Vue.use(Router);
export function createRouter(ssrContext, createDefaultRouter, routerOptions, config) {
const options = routerOptions ? routerOptions : createDefaultRouter(ssrContext, config).options
return new Router({
...options,
routes: [
...options.routes,
{
path: '/blog',
component: ssrContext.req.url.includes('/blog?author') ? BlogAuthorPage : BlogIndexPage
}
]
})
}

Vue 3 dynamic components at router level

Dynamic imports is needed for me, eg. i have 10 layouts, but user only visited 3 layouts, I should not import all of the layouts, since its consumed unnecessary resources.
Since its dynamic import, each time i switch between Login & Register path <RouterLink :to"{name: 'Login'}" /> & <RouterLink :to"{name: 'Register'}" />, I got rerender or dynamic import the layout again.
My question is what is the better way to handle it, without rerender or dynamic import the layout again? Or can I save the dynamic import component into the current vue 3 context?
App.vue this is my app with watching the router and switch the layout based on route.meta.layout
<template>
<component :is="layout.component" />
</template>
<script>
import DefaultLayout from "./layout/default.vue";
import {
ref,
shallowRef,
reactive,
shallowReactive,
watch,
defineAsyncComponent,
} from "vue";
import { useRoute } from "vue-router";
export default {
name: "App",
setup(props, context) {
const layout = shallowRef(DefaultLayout);
const route = useRoute();
watch(
() => route.meta,
async (meta) => {
if (meta.layout) {
layout = defineAsyncComponent(() =>
import(`./layout/${meta.layout}.vue`)
);
} else {
layout = DefaultLayout;
}
},
{ immediate: true }
);
return { layout };
},
};
</script>
router/index.js this is my router with layout meta
import { createRouter, createWebHistory } from "vue-router";
import Home from "#/views/Home.vue";
import NotFound from "#/views/NotFound.vue";
const routes = [
{
path: "/",
name: "Home",
component: Home,
},
{
path: "/login",
name: "Login",
meta: {
layout: "empty",
},
component: function () {
return import(/* webpackChunkName: "login" */ "../views/Login.vue");
},
},
{
path: "/register",
name: "Register",
meta: {
layout: "empty",
},
component: function () {
return import(/* webpackChunkName: "register" */ "../views/Register.vue");
},
},
{ path: "/:pathMatch(.*)", component: NotFound },
];
const router = createRouter({
history: createWebHistory(import.meta.env.VITE_GITLAB_BASE_PATH),
routes,
scrollBehavior(to, from, savedPosition) {
// always scroll to top
return { top: 0 };
},
});
export default router;
You could use AsyncComponent inside the components option and just use a computed property that returns the current layout, this will load only the current layout without the other ones :
components: {
layout1: defineAsyncComponent(() => import('./components/Layout1.vue')),
layout2: defineAsyncComponent(() => import('./components/Layout2.vue')),
},
Had this issue and Thorsten Lünborg of the Vue core team helped me out.
add the v-if condition and that should resolve it.
<component v-if="layout.name === $route.meta.layout" :is="layout">

Redirect to specific url in case of wrong url in vuejs

I have two separate routing files where I am importing the component and defining their routing in each of its file and using it in index.js file. Here are my files code:
//router1.js
import Layout1 from 'Layouts/Panel.vue';
const Users = () => import('Views/Users.vue');
const Reports = () => import('Views/Reports.vue');
export default {
path: '/layout1',
component: Layout1,
redirect:'/layout1/reports',
children:[
{
path: 'reports',
component: Reports,
name:'Reports'
},
{
path: 'users',
component: Users,
name:'Users'
}
]
}
//router2.js
import Layout2 from 'Layout/Panel2';
const Demo1 = () => import('Views/Demo1');
const Demo2 = () => import('Views/Demo2');
export default {
path: '/',
component: Layout2,
redirect:'/demo1',
children:[
{
path: '/demo1',
component: Demo1
},
{
path: '/demo2',
component: Demo2
}
]
}
// index.js
import Vue from 'vue'
import Router from 'vue-router'
import router1 from './router1';
import router2 from './router2';
const NotFound = () => import('Views/NotFound.vue');
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
router1,
router2,
{
path: '*',
component: NotFound,
name:'NotFound',
},
]
})
Now, I want to redirect to specific url i.e "not-found" in case of wrong URL. In "NotFound" component I am adding below line of code in mounted lifecycle hook which redirects to URL "not-found".
this.$router.replace({ path: 'not-found' });
But if URL is having parameters or query string it will append to it. For e.g- http://localhost:8080/home/not-found
What I want is that it only shows http://localhost:8080/not-found How should I achieve this. Please help. Thanks!
try this in your mounted function. worked on my side.
this.$router.push({path: '/not-found'})