vue地址栏直接输入路由无效问题(回车也无效)

参考网址:https://www.jianshu.com/p/06b004c6772f

vue 项目只要不是静态页面,一般都会和官方的路由管理器 vue-router 一起使用。

最近项目有一个需求,是在地址栏输入路由,跳转到对应路由组件,在开发环境中这样做是可以跳转的,但是项目打包后,路由可以访问,但是回车会有404页面的报错

因为 vue 在页面上显示哪个组件是根据 vue-router 进行控制的,在地址栏上直接输入路由名称,并不能触发 vue-router 的规则,所以只能通过监听地址的改变,利用回调函数在组件内部进行动态修改路由。

方式:hashchange 事件

App.vue 中添加此事件:

mounted(){
    window.addEventListener('hashchange',()=>{
        var currentPath = window.location.hash.slice(1); // 获取输入的路由
        if(this.$router.path !== currentPath){
            this.$router.push(currentPath); // 动态跳转
        }
    },false);
}

需要在main.js中将// mode:"history" 注释掉

const router = new VueRouter({

routes : routes,

// mode:"history"

})

猜你喜欢

转载自blog.csdn.net/zezeadede555/article/details/89191004