来自路由器参数的无效道具类型,预期数字得到字符串
Invalid prop type from router params, expected Number got String
我正在尝试从 URL 收集 id
值。
之前我在post寻求帮助。
在我的 index.js
路由器文件中,我有以下代码:
{ path: '/word/:id',
name: 'word',
component: Word,
props: true,
},
在我的组件中有以下代码:
<script>
export default {
props: {
id: Number,
},
created() {
this.routeChanged();
},
watch: {
'id': 'routeChanged',
},
methods: {
routeChanged () {
console.log(this.id);
},
},
};
</script>
我遇到以下错误:
[Vue warn]: Invalid prop: type check failed for prop "id". Expected Number, got String.
这是使用 Function mode 将 Props 传递给路由组件的用例:
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.
在您的情况下,您可以将函数传递给 props
选项,而不是使用 props: true
指定路由选项:
routes = [{
path: '/word/:id',
component: Word,
props: castRouteParams
}];
function castRouteParams(route) {
return {
id: Number(route.params.id),
};
}
实例:https://codesandbox.io/s/8kyyw9w26l(点击"Go to Test/3" link)
我正在尝试从 URL 收集 id
值。
之前我在
在我的 index.js
路由器文件中,我有以下代码:
{ path: '/word/:id',
name: 'word',
component: Word,
props: true,
},
在我的组件中有以下代码:
<script>
export default {
props: {
id: Number,
},
created() {
this.routeChanged();
},
watch: {
'id': 'routeChanged',
},
methods: {
routeChanged () {
console.log(this.id);
},
},
};
</script>
我遇到以下错误:
[Vue warn]: Invalid prop: type check failed for prop "id". Expected Number, got String.
这是使用 Function mode 将 Props 传递给路由组件的用例:
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.
在您的情况下,您可以将函数传递给 props
选项,而不是使用 props: true
指定路由选项:
routes = [{
path: '/word/:id',
component: Word,
props: castRouteParams
}];
function castRouteParams(route) {
return {
id: Number(route.params.id),
};
}
实例:https://codesandbox.io/s/8kyyw9w26l(点击"Go to Test/3" link)