如果vue.js中的URL错误,则重定向到特定的URL

时间:2019-07-10 06:05:02

标签: vuejs2 vue-router

我有两个单独的路由文件,我在其中导入组件并在每个文件中定义它们的路由,并在index.js文件中使用它。这是我的文件代码:

//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',
        },
    ]
})

现在,如果URL错误,我想重定向到特定的URL,即“找不到”。在“未找到”组件中,我在 mount 生命周期挂钩中添加了以下代码行,该代码重定向到URL“未找到”。

  

this。$ router.replace({path:'not-found'});

但是,如果URL具有参数或查询字符串,它将附加在其后。例如- http://localhost:8080/home/not-found 我想要的是它仅显示 http://localhost:8080/not-found 我应该如何实现。请帮忙。谢谢!

1 个答案:

答案 0 :(得分:2)

在已安装的函数中尝试此操作。在我这边工作。

this.$router.push({path: '/not-found'})