我正在尝试收集 id
来自 URL 的值。
以前我在 this 帮忙邮政。
在我的 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 将 Prop 传递到路由组件的用例:
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: true
指定路由选项,你会传递一个函数给 props
选项:routes = [{
path: '/word/:id',
component: Word,
props: castRouteParams
}];
function castRouteParams(route) {
return {
id: Number(route.params.id),
};
}
现场示例:https://codesandbox.io/s/8kyyw9w26l (单击“转到测试/3”链接)
关于vuejs2 - 来自路由器参数的无效 Prop 类型,预期数字得到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51418072/