Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid prop type from router params, expected Number got String

I am trying to collect id value from URL.

Previously I take help in this post.

In my index.js of router file I have below code:

{   path: '/word/:id',
    name: 'word',   
    component: Word,
    props: true,
}, 

In my component I have below code:

<script>
    export default {
        props: {
             id: Number,
        },
        created() {
             this.routeChanged();
        },
        watch: {
            'id': 'routeChanged',
        },
        methods: {
            routeChanged () {
                console.log(this.id);
            },
        },
    };
</script>

I am getting below error:

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

like image 837
abu abu Avatar asked Jul 19 '18 08:07

abu abu


1 Answers

That is the use case for Passing Props to Route Components with Function mode:

You can create a function that returns props. This allows you to cast parameters into other types, combine static values with route-based values, etc.

In your case, instead of specifying the route option with props: true, you would pass a function to the props option:

routes = [{
  path: '/word/:id',
  component: Word,
  props: castRouteParams
}];

function castRouteParams(route) {
  return {
    id: Number(route.params.id),
  };
}

Live example: https://codesandbox.io/s/8kyyw9w26l (click on the "Go to Test/3" link)

like image 74
ghybs Avatar answered Nov 03 '22 05:11

ghybs