C
C
coder562020-08-17 15:38:45
Vue.js
coder56, 2020-08-17 15:38:45

How to display the filtered array on button click?

Given a button. Given an array of numbers. It is necessary to display the elements of this array as a ul list.
By pressing the button, only those elements should remain on the screen, the number of which is greater than 0, but less than 10.
Code:

<div id="app">
 <button v-on:click="filterMassive">Отфильтровать</button>
  <ul>
    <li v-for="item in filterMassive(items)">{{ item }}</li>
  </ul>
</div>

let app = new Vue({
    el: '#app',
    data: {
        items: [8,6,22,15,14,9,7,5,3]
    },
    methods: {
        filterMassive: function (items) {
            return items.filter(function (item) {
                return item >0 && item <10;
            });
        }
    },
});

How can I make vue output the filtered array on button click instead of immediately like in the code above?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-08-17
@coder56

<button @click="showFiltered = !showFiltered">
  Показать {{ showFiltered ? 'все' : 'отфильтрованные' }} элементы
</button>
<ul>
  <li v-for="n in (showFiltered ? filteredItems : items)">{{ n }}</li>
</ul>

data: () => ({
  items: [ ... ],
  showFiltered: false,
}),
computed: {
  filteredItems() {
    return this.items.filter(n => 0 < n && n < 10);
  },
},

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question