在道具功能

时间:2018-01-14 17:27:57

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

我有这个路线定义:

{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.

所以我用道具功能

更新我的路线定义
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 param的值(" / article / toto"例如)

router.onError似乎不在这里工作

导航警卫,其中可以使用下一个(错误)无法修改参数/道具

有人有任何想法吗?

1 个答案:

答案 0 :(得分:0)

网址参数中的所有值均为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
      }
    }
  }

现在,在设置监视器时,您可以使用Regex检查prop中的当前值是否为Number或String类型。

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