VUE v-for value filter

Asked

Viewed 423 times

1

I have the following object array below. I need to list in a v-for only records where the variable parent be equal to 4, and I’m not getting it.

Code:

this.full_category_list = [
    {
        id: 1, 
        name: 'Sólido',
        parent : 0,
    },
    {
        id: 2, 
        name: 'Líquido',
        parent : 0
    },
    {
        id: 3, 
        name: 'Madeira',
        parent : 1
    },
    {
        id: 4, 
        name: 'Ferro',
        parent : 1
    },
    {
        id: 5, 
        name: 'Chapas',
        parent : 4
    },
    {
        id: 6, 
        name: 'Tubos',
        parent : 4
    },
    {
        id: 7, 
        name: 'Vigas',
        parent : 4
    },
];
  • 1

    Create a computed property that matches this list. And in v-for use this property.

1 answer

10


You can use the computed to solve the problem.

Thus:

new Vue({

    el: '#app',

    data: {

        meus_valores: [/** **/]
    },


    computed: {

        meus_valores_filtrados: function () {

            return meus_valores.filter(function (valor) {
                return valor.parent === 4;
            })
        }
    }
})

In your view, you display like this:

<li v-for="valor in meus_valores_filtrados">
    <!-- sua lógica aqui ->
</li>

I set an example in the snippet, for you to see working "live".

Check it out:

new Vue({
    el: '#app',
    data: {

        valores: [

            {
                   id: 1, 
                   name: 'Sólido',
                   parent : 0,
            },

            {
                   id: 2, 
                   name: 'Líquido',
                   parent : 0
            },

            {
                   id: 3, 
                   name: 'Madeira',
                   parent : 1
            },

            {
                   id: 4, 
                   name: 'Ferro',
                   parent : 1
            },

            {
                   id: 5, 
                   name: 'Chapas',
                   parent : 4
            },

            {
                   id: 6, 
                   name: 'Tubos',
                   parent : 4
            },

            {
                   id: 7, 
                   name: 'Vigas',
                   parent : 4
            },

        ]
    },

    computed: {

        valores_filtrados: function () {

            return this.valores.filter(function (valor) {
                return valor.parent === 4;
            })
        }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>

<div id="app">
    <li v-for="valor in valores_filtrados">
       {{ valor.id }} - {{ valor.name }}
    </li>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.