how i make filter search in vue js with javascript

can i write a filter search code with just data and methods function?

i try do this :

var fil = new Vue ({
            el: '#app',
            data: {
                search: '',
                proL: ['css', 'c++', 'cs#'],
            },
            methods: {
                filter: function(){

                        var search_key = this.search.val();
                        
                        this.proL.filter(function(){
                            this.proL.toggle(this.proL.text().indexOf(search_key) > -1);
                        });

                }
            }
        });

and this is the html code

<div id="app">
        <div >
          <input @keyup="filter()" type="text" v-model="search" placeholder="Search title.."/>
        </div>

        <div id="pro">
            <h4 v-for="item in proL">{{item}}</h4>
        </div>
    </div>

😅😅

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Try to use a computed property to define the filtered items and use an arrow function as filter function callback in order to get access to this:

new Vue({
  el: '#demo',
  data: {
      search: '',
      proL: ['css', 'c++', 'cs#'],
  },
  computed: {
    filtered(){
      return this.proL.filter(e => e.toLowerCase().includes(this.search.toLowerCase()))
    }
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div >
    <input type="text" v-model="search" placeholder="Search title.."/>
  </div>

  <div id="pro">
      <h4 v-for="item in filtered">{{item}}</h4>
  </div>
</div>

Method 2

A better approach would be using computed handler

new Vue({
  el: '#demo',
  data: {
      search: '',
      proL: ['css', 'c++', 'cs#'],
  },
  computed: {
    filteredProL(){
      if(this.search === '') return this.proL; // If search input is empty then display all items
      else return this.proL.filter(e => e.toLowerCase().indexOf(this.search) > -1) // Working logic
    }
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div >
    <input type="text" v-model="search" placeholder="Search title.."/>
  </div>

  <div id="pro">
      <h4 v-for="item in filteredProl">{{item}}</h4>
  </div>
</div>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x