首页 > 解决方案 > vue prop 始终是子组件中的默认值

问题描述

我正在将一堆道具从父组件传递给子组件。在我的子组件中,我为所有道具定义了一个默认值。

Overview.vue (child)

  props: {
    name: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    },
    username: {
      type: String,
      default: ''
    },
    email: {
      type: String,
      required: true,
      default: ''
    },
    phone: {
      type: Number,
      default: null
    },
    status: {
      type: String,
      required: true,
      default: ''
    },
    statusOptions: {
      type: Array,
      default: () => []
    }
  },

我的父母看起来像这样:

UserSettings.vue (parent)

          <overview
            :name="name"
            :username.sync="username"
            :email="email"
            :status="status"
            :status-options="statusOptions"
            @update-username="username = $event"
          />

UserSettings.vue data (parent)

  data() {
    return {
      name: 'John',
      username: 'Nevermind',
      email: 'john.nevermind@okey.com',
      status: 'idle',
      statusOptions: ['idle', 'vacation', 'working']
    }
  }

在我的孩子comp中,我想像这样将传递的数据保存在我的内部data()

Overview.vue (child)

  data() {
    return {
      overviewData: {
        username: this.username,
        email: this.email,
        phone: this.phone,
        status: this.status
      }
    };
  },

现在的问题是,在我的overviewData所有道具中的子组件内部都设置为默认值,并且它没有采用传递的道具值。

标签: javascriptvue.jsvue-props

解决方案


我怀疑您在其中显示数据的方式存在错误<overview>(或以其他方式确定它为空白)。请参阅此处的工作沙箱。请随时使用概述实现进行编辑,以便我们为您排序。


推荐阅读