【问题标题】:Prop shows in Dev tools but shows undefined when used道具显示在开发工具中,但在使用时显示未定义
【发布时间】:2019-09-30 08:20:15
【问题描述】:

我正在将一个简单的 ID 传递给子组件,但有一个未定义的控制台日志错误,并且无法使用该道具

我把这里的道具传给孩子

<transactions v-show="active_tab == 2" :userId="affiliate.user_id"></transactions>

然后在孩子这里捡到

props: ["userId"]

然后我只是尝试像这样控制台记录道具

console.log(this.userId);

从图片中可以看出,道具出现在 Devtools 中

错误如下

[Vue 警告]:无效的道具:道具“userId”的类型检查失败。预期值为“未定义”的字符串,得到未定义

【问题讨论】:

  • 请贴出错误,以及其他相关代码。目前我们不知道在哪里调用了任何函数。
  • 您的大小写错误。使用:user-id="affiliate.user_id"
  • 这可能是一个种族问题,不知道你从哪里得到你的 id 但试试:userId="someConstant" 看看是否有效。在这种情况下,您可以尝试一些方法,一种选择是在具有值的道具上渲染子组件:v-if="affiliate.user_id"

标签: vue.js vuejs2 prop


【解决方案1】:

尝试使用这样的模板调用:

<transactions v-if="active_tab == 2" :user-id="affiliate.user_id"></transactions>

vue 编译可以将模板上的驼峰式 props 更改为带连字符的小写。

您可以查看有关此的 vue 文档:https://vuejs.org/v2/guide/components-props.html#Prop-Casing-camelCase-vs-kebab-case

【讨论】:

    【解决方案2】:

    所以看起来 prop 是在页面加载后声明的,所以我使用 Watch 等待更改然后运行该方法

    原来如此

    watch: {
        user_id() {
          console.log(this.user_id);
          this.fetch_transactions_data();
        }
      }
    

    【讨论】:

    • 或者,在组件上使用条件渲染来等待值,例如&lt;transactions v-if="affiliate.user_id" :user-id="affiliate.user_id"...
    猜你喜欢
    • 2020-09-15
    • 2012-05-12
    • 2011-10-19
    • 2015-05-24
    • 2012-07-02
    • 2017-07-30
    • 2023-03-12
    • 2017-05-21
    • 2017-06-16
    相关资源
    最近更新 更多