[Vuejs]-Vue JS prop in component always undefined

0👍

The subcat prop is undefined because you are not passing it to the component. But, a subcat prop doesn’t make much sense anyway, since you want to check the value for each option in the select which could all be different.

If you compose the options inside of the component definition:

// child component script
props: ['value', 'options'],
// child component template
<template>
  <select>
    <slot>
      <option 
        v-for="option in options" 
        :key="option.id"
        :value="option.id" 
        :subcat="option.subcat" 
        v-text="option.text"
      ></option>
    </slot>
  </select>
</template>

And then pass a correctly formatted options prop to the component:

// parent component script
computed: {
  options() {
    return this.cats.map((cat) => {
      return {
        id: cat.cat_id,
        subcat: cat.has_subcat,
        text: cat.category_name
      }
    });
  }
}
// parent component template
<material-selectcat v-model="catId" :options="options" name="category" id="selcat">
</material-selectcat>

Then, you could get the correct subcat value for any option’s corresponding value by referencing the options prop in the fetchSubCategories method:

fetchSubCategories: function(val) {
  var mdl = this;
  var catID = val || this.value;
  var sub = (this.options.find(o => o.id === val) || {}).subcat;
  ...

The reason your value prop is defined in your code is that you are using the v-model directive on the component tag. The v-model directive is just syntactic sugar for :value="something" @input="something = $event.target.value". Since you’ve specified catID as the v-model, that will be passed to your component as the value prop.

Leave a comment