【问题标题】:Vue.JS - Both 'history' and 'hash' router?Vue.JS - “历史”和“哈希”路由器?
【发布时间】:2020-02-13 18:32:50
【问题描述】:

我正在开发一个 Vue.Js 站点并使用 Vue-router 默认模式“哈希”。所以网站 URL 是这样的:

www.mysite.com/#/Home

此网站已被某些移动应用程序链接,我无法更改它们。但是我有一个新要求,我需要更改 URL 以从 URL 中删除哈希 (#)。所以我将 Vue-router 模式更改为“历史”,现在我的网站在没有哈希的情况下工作。像这样:

www.mysite.com/Home

问题是使用历史模式时,带有井号 (#) 的 URL 不起作用。但是为了与将网站链接到哈希的移动应用程序兼容,我仍然需要使带有哈希的 URL 有效。

问题:

如何使用 Vue-router 历史模式并保持带有哈希的 URL 正常工作?

我在 router/index.js 文件中尝试了以下方式:

export default new Router({
  mode: 'history',
  routes: [
    {
        path: '/Home',
        name: 'Home1',
        component: Home
    },
    {
        path: '/#/Home',
        name: 'Home2',
        component: Home
    },
    ...
]})

使用此配置,网址 www.mysite.com/Home 有效,但网址 www.mysite.com/#/Home 无效。

【问题讨论】:

标签: vue.js vue-router


【解决方案1】:

对我来说,我只需要将外部旧链接路由到当前历史模式。

在 App.vue 中挂载:

if (location.hash) {
  location.replace(location.hash.replace('#', ''))
}

【讨论】:

    【解决方案2】:

    我根据 @Ohgodwhy 和 a question/answer 来自 vue.js 论坛的评论回答我自己的问题,@nathany 已回答。

    解决方案是从具有散列的 URL 中删除 has (#),并将其重定向到没有散列的 URL。可以在方法 router.beforeEach() 中完成。

    我的 router/index.js 是这样的:

    import Vue from 'vue'
    import Router from 'vue-router'
    import Home from '@/components/Home'
    
    export default new Router({
          mode: 'history',
          routes: [
            {
                path: '/Home',
                name: 'Home',
                component: Home
            },
          ],
    })
    

    然后我改成:

    import Vue from 'vue'
    import Router from 'vue-router'
    import Home from '@/components/Home'
    
    var router = new Router({
          mode: 'history',
          routes: [
            {
                path: '/Home',
                name: 'Home',
                component: Home
            },
          ],
    })
    export default router;
    
    router.beforeEach((to, from, next) => {
        // Redirect if fullPath begins with a hash (ignore hashes later in path)
        if (to.fullPath.substr(0,2) === "/#") {
            const path = to.fullPath.substr(2);
            next(path);
            return;
        }
        next();
    });
    

    【讨论】:

    • 不幸的是,这在当前版本或当前浏览器中不再起作用。我不确定是谁对此负责。完整路径没有“#”。
    猜你喜欢
    • 2019-06-06
    • 2017-08-23
    • 2017-06-11
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 2023-03-09
    相关资源
    最近更新 更多