5

I have a v-data-table bound to a search prop, and a v-text-field with clearable set. When I clear the text field with the clearable icon-button, v-text-field sets the search prop to null, causing my computed prop to error out with:

Cannot read property toLowerCase() of null

How can I set the search prop back to an empty string instead of null when the clearable icon is clicked?

MyComponent.vue:

<template>
  <div>
    <v-text-field solo hide-details single-line v-model="search" clearable>
    </v-text-field>

    <v-data-table :search="search" class="mt-2" :items="myArray" hide-actions hide-headers elevation-1>
      <template v-slot:items="props">
        <td>{{props.item.myItems}}</td>
      </template>    
    </v-data-table>
  </div>
</template>

<script>
export default {
  props: ['parameter'],
  data() {
    return {
      search: ''
    }
  },
  computed: {
    myArray() {
      let myArray = []
      if(this.parameter) {
        myArray = this.parameter.filter((download) => {                
          return download.barcode.includes(this.search.toLowerCase());
        })
      }
      return myArray;
    }
  }
}
</script>
tony19
  • 125,647
  • 18
  • 229
  • 307
Somethingwhatever
  • 1,390
  • 4
  • 32
  • 58

3 Answers3

2

Try to check the search data property as a condition inside the return statement :

  if(this.parameter) {
      myArray = this.parameter.filter((download) => {                
            return !this.search || download.barcode.includes(this.search.toLowerCase());
        })
    }
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
2

Try using @click:clear="clearFunction()" as mentioned here.

Codepen reference: https://codepen.io/anon/pen/ePmLOg?editors=1010

Kousika Ganesan
  • 539
  • 1
  • 6
  • 22
0

No need to translate search's null to empty string. Just update the computed prop to check for a truthy search value:

let myArray = []

if (this.parameter && this.search ) {
  myArray = this.parameter.filter((download) => {
    return download.barcode.includes(this.search.toLowerCase())
  })
}

return myArray

Edit Filtering items in v-data-table

tony19
  • 125,647
  • 18
  • 229
  • 307