如何在 Vue js 中将对象作为 prop 传递?

问题描述 投票:0回答:1

我认为传递对象与数组类似,我只需要避免 v-for 循环。但在这种情况下,我得到的 prop 是未定义的。

<template>
  <p>{{info.text...}}</p>
</template>

export default {
  props: {
    info: {
      type: Object,
      default: () => ({})
    }
  },
  mounted () {
    console.log(this.info)       // gets undefined
  }
}
javascript vue.js object undefined prop
1个回答
0
投票

在 Vue.js 中将对象作为 prop 传递与传递其他类型的 prop 类似,但使用方式可能存在问题。

首先,确保您在使用子组件的模板中正确地将

info
属性从父组件传递到子组件。

例如,如果您在父组件的模板中使用子组件,则应该像这样传递

info
属性:

<template>
  <child-component :info="infoObject" />
</template>

接下来,确保

infoObject
存在并在父组件的数据中定义。

export default {
  data() {
    return {
      infoObject: {
        text: 'Some text',
        // other properties...
      },
    };
  },
};

现在,在您的子组件中,您可以访问

info
属性并按如下方式使用它:

<template>
  <p>{{ info.text }}</p>
</template>

<script>
export default {
  props: {
    info: {
      type: Object,
      default: () => ({}),
    },
  },
  mounted() {
    console.log(this.info); // Should print the infoObject with text property
  },
};
</script>

通过执行这些步骤,您应该能够将对象作为 prop 传递并在子组件中访问其属性。如果您仍然遇到

undefined
,请仔细检查您是否正确地从父组件传递了 prop,并且该对象是否使用适当的属性进行了定义。

© www.soinside.com 2019 - 2024. All rights reserved.