【问题标题】:Redirect Vue-Router on error in props function在道具功能错误时重定向 Vue-Router
【发布时间】:2018-06-23 10:46:46
【问题描述】:

我有这个路线定义:

{name: "article", path: "/article/:id", component: Article, props: true}

还有这个组件(我使用 Typescript 和 vue-class-component):

@Component({
    props: {
        id: Number
    }
})
class Article extends Vue {
    id: Number;
}

当然,这给我这个警告

[Vue warn]: Invalid prop: type check failed for prop "id". Expected Number, got String.

所以我用 props 函数更新了我的路线定义

name: "article", 
path: "/article/:id", 
component: Article, 
props:(route:Route) => {
    const id = parseInt(route.params.id);

    if(isNaN(id))
        throw new Error("id param should be a number")

    return {id}
}

这可行,但如果他给我一个“错误”的 id 参数值(例如“/article/toto”),我不知道如何将用户重定向到特定页面

router.onError 似乎在这里不起作用

导航守卫,其中 in can use next(error) can't modify params/props

有人知道吗?

【问题讨论】:

    标签: vuejs2 vue-router vue-class-components


    【解决方案1】:

    URL 参数中的所有值都是type String

    在您的组件中,为此特定属性设置监视

    props : ["id"],
    watch : {
        id(current,previous){
          var reg = /^\d+$/;
          if(reg.test(current)){
            console.log("its a number");
          }
          else{
            console.log("its not a number");
            this.$router.push("/error"); //HomeComponent or ErrorComponent
          }
        }
      }
    

    现在手表设置好了,你可以使用正则表达式检查你在 prop 中的当前值是数字还是字符串类型。

    if currentValue is Number then 
        GoAhead
    if currentValue is NAN then 
        Redirect to HomeComponent or ErrorComponent
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-17
      • 2019-09-27
      • 2016-09-16
      • 1970-01-01
      • 2016-02-21
      • 2018-11-20
      • 2019-07-18
      • 2021-12-26
      相关资源
      最近更新 更多