vuejs2 - 来自路由器参数的无效 Prop 类型,预期数字得到字符串

标签 vuejs2 vue-router

我正在尝试收集 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/

相关文章:

javascript - 使用 v-onclick Vue 2.0 隐藏父级。最大宽度 : 767px

vue.js - 在 vue.js keep-alive 部分刷新页面

vue.js - 通过关键参数保持事件 View 路由器

javascript - 为什么Vue事件不向上传播?

javascript - 如何在 Laravel 应用程序上的 axios 中配置 header

javascript - Vue.js : How to generare multiple dynamic ID's with a defined pattern

vue.js - vuejs属性中的语法 `${k}`是什么?

javascript - 如何在 Vue.js 2 应用程序中模拟 onbeforeunload?

javascript - Vue 计算的 setter 不会为 v-model 中的数组触发

javascript - "Unknown custom element: <router-view> - did you register the component correctly?"的任何解决方案