[Vuejs]-Loop through a computed property Vue

2πŸ‘

βœ…

You are using return which will stop further execution of function. You can create a variable and inside loop concat the values to that variable and return it in the end.

var app = new Vue({el: '#app',data() {return
{permissions: [
        {id:1,name:'create'},
        {id:2,name:'edit'},
        {id:3,name:'delete'}]
    }
  },
  computed: {
     getFormPermissionId(){
       var permission = this.permissions
       let result = '';
       for(let i = 0;i < permission.length; i++ ) {
         result += permission[i] + '<br>'
       }
       return result;
     }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">  
  {{getFormPermissionId}}
</div>
πŸ‘€Maheer Ali

1πŸ‘

You can create string and can do the same

var app = new Vue({
    el: '#app',
    data() {
        return {
            permissions: [{
                    id: 1,
                    name: 'create'
                },
                {
                    id: 2,
                    name: 'edit'
                },
                {
                    id: 3,
                    name: 'delete'
                }
            ]
        }
    },
    computed: {
        getFormPermissionId() {
            var permission = this.permissions;
            //Creating String 
            str = "";
            for (let i = 0; i < permission.length; i++) {
                 str += permission[i].id + "\n";
            }
            return str;
        }
    }
})

Complete Example

    var app = new Vue({
        el: '#app',
        data() {
            return {
                permissions: [{
                        id: 1,
                        name: 'create'
                    },
                    {
                        id: 2,
                        name: 'edit'
                    },
                    {
                        id: 3,
                        name: 'delete'
                    }
                ]
            }
        },
        computed: {
            getFormPermissionId() {
                var permission = this.permissions;
                //Creating String 
                str = "";
                for (let i = 0; i < permission.length; i++) {
                    str += permission[i].id + "\n";
                }
                return str;
            }
        }
    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">  
  {{getFormPermissionId}}
</div>

0πŸ‘

Here’s what you can do:

<div id="app">  
 <div v-for="(item, index) in permissions" :key="index">
    {{item.id}}
    <br/>
  </div>
</div>

And you can just remove the computed.

πŸ‘€Sheng

Leave a comment