【问题标题】:How can i return 404 error without change url in Vue?如何在不更改 Vue 中的 url 的情况下返回 404 错误?
【发布时间】:2019-08-05 23:30:20
【问题描述】:

问题

使用 Vue.js,如何在不更改 url 的情况下在动态路由中返回 404 错误?

我的 route.js 的一部分(一切正常)

{

    path: '/work/:id',
    name: 'work',
    component: () => import( './views/Work.vue' )

},

{

    path: '*',
    name: 'NotFound',
    component: () => import( './views/NotFound.vue' )

}

Work.vue 组件的一部分。我在哪里检查路由参数是否在我的静态 json 中,如果没有,请在路由输入之前打开 NotFound 组件

beforeRouteEnter (to, from, next) {
    next(vm => {
        vm.item = json.find(item => item.id == vm.$route.params.id)

        if(!vm.item) {
            next({name: NotFound})
        }

    })
}

问题

当我尝试 site.com/work/non-existent-id 时,“NotFound”组件打开,但网址来自 site.com/work/non-existent- idsite.com

我的看法

site.com/work/non-existent-id 打开组件“NotFound”,网址保持在site.com/work/non-existent-id

例子

https://vuejs.org/v2/guide/something - 返回 404 错误并停留在 url 中

【问题讨论】:

    标签: javascript vue.js http-status-code-404 vue-router


    【解决方案1】:

    路由器旨在完全按照您希望它们不做的事情来做。如果您想在应用程序的任何路由上显示一些内容,我建议您创建一个新组件并触发一个事件以显示您想要的任何内容。

    就个人而言,我认为重新路由将是可行的方法,因为这将允许用户点击浏览器中的后退按钮以返回他们来自的位置,但我想这一切都取决于您的具体用途案例在这里。

    【讨论】:

      【解决方案2】:

      我仍在使用 vue router3 并且在不更改 url 的情况下为我工作。 对于 axios。

      beforeRouteEnter(to,from,next) {
       axios
       .get(`http://localhost:5000/api/product/${to.params.id}`)
       .then((res) => {
          next((vm) => {
            vm.product = res.data;
            next();
          });
        })
        .catch((error) => {
           
            next({ name: 'notFound', params: [to.path]});
          
          
        });
      }
      

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 2019-03-28
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 2017-02-16
      • 1970-01-01
      • 2022-06-15
      相关资源
      最近更新 更多