Skip to content Skip to sidebar Skip to footer

Relationship Between Props And Data (vue)

In https://codesandbox.io/s/v9pp6 the ChromePage component passes a prop to InventorySectionC:

Solution 1:

(this grew too long for a comment, but probably already answers what you need)

itemSectionProps:

Your props are defined as:

props: {
    itemSectionProps: {
      type: Object,
    },
  },

You reference a prop of that object in your template

<draggablev-model="itemSectionProps.itemSectionCategory">

Vue cannot assume itemSectionProps.itemSectionCategory will exist in the future. You should give it a default (see Vue docs) to create the expected values in that object.

props: {
    itemSectionProps: {
      type: Object,
      default() {
        return { itemSectionCategory: '' };
      }
    },
  },

Do this for all the props you use on itemSectionProps.

data() can't seem to see props:

You can write this.itemSectionProps instead of only itemSectionProps. But itemSectionProps is already defined in props. You can just remove itemSectionProps from data.

If you need to change that value, use a copy and promote changes with this.$emit.

Solution 2:

You are probably calling the props without using this. on your data method.

You can as well define your variable itemSectionData as below:

data(){ 
       return {
           itemSectionData: Object.assign({}, this.itemSectionProps)
        }
    }

Object.assign() The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object. See more details here

Then use the newly defined variable itemSectionData within your component. Like:

<draggablev-model="itemSectionData.itemSectionCategory">

If you want to update the prop's values, simply emit an event from your child component and capture it on the parent as below:

methods:{
     updatePropValues(){
        this.$emit('updateProp', this.yourNewValues);
      }
    }

On the parent component handle the event as:

<inventory-section-component @updateProp="setNewValues" :itemSectionProps="getItemSection">
  </inventory-section-component>

methods:{
  setNewValues(newValues){
     this.itemSections = newValues;
   }
}

Check it out in action here

Post a Comment for "Relationship Between Props And Data (vue)"