[Vuejs]-Call a function (with parameters) inside a v-for element (Vue.js)

2👍

Finally I resolved myself with a different approach. Hope maybe helps someone.

Instead of calling a function in the for option I previously call the API to check if it’s previously selected and add an attribute to the subItem element.

With the @Ricardo Orellana solution in the first load, I can’t know which item is selected, only when the select value change.

I use the v-bind:class option to check if the subItem is selected and mark:

   <md-select v-if="categories.length > 0" name="categories" id="categories" multiple v-model="selectedNew"> 
      <md-button class="md-icon-button" md-menu-trigger slot="icon">
        <md-icon>{{icon}}</md-icon>      
      </md-button>

      <div v-for="(category,key,index) in categories" :key="category.id">
        <md-subheader>{{category.name}}</md-subheader>
        <md-option 
          v-bind:class="{ 'md-checked' : subItem.selected }"
          v-if="category.subItems" 
          v-for="subItem in category.subItems"
          :key="subItem.id" 
          :value="subItem">
            {{subItem.name}}
        </md-option>      
      </div>
    </md-select>

Then, in the method part:

   ...
   cat.subItems = actobj                
   cat.subItems.map(this.markIsSelected)
   ...

   markIsSelected (cat, index, categories) {
      categories[index].selected = false
      this.selectedOld.forEach(function (catOld) {
        if (cat.id === catOld.optionId) {
          categories[index].selected = true
          return
        }
      })
    }

Thanks for your time and the help!

1👍

You could try to add v-model="currentCategorySelected" and use the function @change="checkIsSelected". That way anytime a new option is selected is going to execute and pass the id selected through the callback.

This should work:

<md-select
  v-if="categories.length > 0"
  name="categories"
  id="categories"
  v-model="currentCategorySelected"
  @change="checkIsSelected"
  multiple>
    <div 
      v-for="(category,key,index) in categories"
      :key="category.id">

      <md-subheader>
        {{category.name}}
      </md-subheader>

      <md-option
        v-if="category.subItems"
        v-for="subItem in category.subItems"
        :key="subItem.id"
        :value="subItem.id"
      >
        {{subItem.name}}
      </md-option>
    </div>
</md-select>

-1👍

You need to change selected="checkIsSelected(subItem.id)" to :selected="checkIsSelected(subItem.id)". Colon.

👤Bsalex

Leave a comment