Home » vue » V-for loop multidimensional call using vuejs

V-for loop multidimensional call using vuejs

Posted by: admin November 26, 2021 Leave a comment

Questions:

I would like all the name and after this if parent is not null it should return parent.name

so data should be

Zack
Computer - mouse
Computer HDD
Laptop - Ram

How can i achieve this here is my code

    <li v-for="(index, item) in inventory">
       {{ item.name }}
    </li>
    <li v-for="par in item.parent"> {{ par.name }} </li>
  </ul>

https://jsfiddle.net/L3gshbna/

This should return those parents is null and then whose parents are there see my expected response thanks

Answers:

You should sort your array first to achieve Zach as first output.
You can do it multiple ways, one of them you can see in my updated fiddle
https://jsfiddle.net/doef2u01/1/

var vm = new Vue({
  el: '#vue-instance',
  data: {
    inventory: [
      {"id":21,"name":"Mouse","parent_id":3,"parent":{"id":3,"name":"Computer","parent_id":null}},
      {"id":1,"name":"Zack","parent_id":null, "parent":null},
      {"id":27,"name":"Ram","parent_id":4,"parent":{"id":4,"name":"Laptop","parent_id":null}},
      {"id":37,"name":"HDD","parent_id":6, "parent":{"id":6,"name":"Computer","parent_id":null}}
    ]
  },
  
  computed: {
      sortedInventory() {
    	return [
      	...this.inventory.filter(item => item.parent === null),
        ...this.inventory.filter(item => item.parent !== null)
      ]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="vue-instance">
  <ul>
    <li v-for="(index, item) in sortedInventory">
       <template v-if="item.parent">
         {{item.parent.name}} -
       </template>
       {{ item.name }} 
    </li>
  </ul>
</div>

###

Try this

<div id="vue-instance">
  <ul>
    <li v-for="(index, item) in inventory">
       {{ item.name }}

    </li>
    <li v-for="par in inventory"> {{ par.parent.name }} </li>
  </ul>
</div>

###

You can achieve this by using v-if and v-else

<div id="vue-instance">
  <ul>
    <li v-for="(i, value)  in inventory">
      <template v-if='value.parent'>
        {{value.parent.name}} - {{ value.name }}        
      </template>
      <template v-else>
        {{ value.name }}        
      </template>
    </li>
  </ul>

###

If I’m unterstanding you right this will give you the result:

<div id="vue-instance">
  <ul>
    <li v-for="(index, item) in sorted">
      <span v-if="item.parent !== null"> {{ item.parent.name }} - </span>   {{ item.name }}
    </li>
  </ul>
</div>
  computed: {
        sorted: function() {
            return this.inventory.sort(item => {
                return item.parent_id !== null;
            });
        }
    }

https://jsfiddle.net/e8z0gbkx/