ahzep
ahzep

Reputation: 180

Filtering a simple number array on vue

I have a simple number array generated at random that is rendered by a v-for, I also want to be able to filter it by writing the desired numbers in a input, I do this by using the vanilla JS filter() method. However it returns the error

TypeError: "num.includes is not a function"

I don't know what am I doing wrong, here's the html:

    new Vue({
      el: "#app",
      data: {
        numberArray: [],
        searching: ''
      },
      methods: {
        random() {
          this.numberArray = Array.from({
            length: 40
          }, () => Math.floor(Math.random() * 40));
        },
        search(){
        return this.numberArray.filter((num) => num.includes(this.searching));
        }
      }
    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

 <div id="app">
      <button @click="random()">
    Generate
    </button>
      <hr>
        <input type="search" v-model="searching" placeholder="search">
      <ul>
        <li v-for="num in search">
          {{ num }}
        </li>
      </ul>
      </div>

Upvotes: 0

Views: 691

Answers (1)

Decade Moon
Decade Moon

Reputation: 34306

includes() is a function defined on strings and arrays, not numbers.

Also search should be a computed property instead of a method.

Did you mean to do this:

computed: {
  search() {
    return this.numberArray.filter(num => String(num).includes(this.searching));
  }
}

Upvotes: 2

Related Questions