How to pass an Object as a prop in Vue js?

291 Views Asked by At

I thought passing an Object is simillar to an array, I just simply need to avoid v-for loop. But in this case I'm getting prop as an undefined.

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

export default {
  props: {
    info: {
      type: Object,
      default: () => ({})
    }
  },
  mounted () {
    console.log(this.info)       // gets undefined
  }
}
2

There are 2 best solutions below

0
AdityaDees On BEST ANSWER

Passing an object as a prop in Vue.js is similar to passing other types of props, but there might be an issue with how you are using it.

First, make sure you are correctly passing the info prop from the parent component to the child component in the template where the child component is used.

For example, if you are using the child component in the parent component's template, you should pass the info prop like this:

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

Next, make sure that the infoObject exists and is defined in the parent component's data.

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

Now, in your child component, you can access the info prop and use it as follows:

<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>

By following these steps, you should be able to pass an object as a prop and access its properties in your child component. If you are still getting undefined, please double-check that you are correctly passing the prop from the parent component and that the object is defined with the appropriate properties.

0
user1730452 On

One should note that using the Vue3 Composition API you have to access the object using props.myObject. This means you have to define the props using const props = defineProps({ myObject: {type: Object}...}) logic.

You can still access simple values without the "props." prefix, but objects require it for some reason.

Also, note the class name begins in lowercase seems to be the only way it works.