[Vuejs]-Vue computed property not recomputing as I would have expected

0👍

What I ran into turning your example code into a snippet was some of the camel case/kebab case issue: HTML is case-insensitive, so the event should be kebab-case, not camelCase. This example filters as expected.

new Vue({
  el: '#app',
  data: {
    searchCriteria: '',
    documents: [{
        filename: 'FirstFile'
      },
      {
        filename: 'SecondFile'
      },
      {
        filename: 'LastOne'
      }

    ]
  },
  methods: {
    updatedSearchString(searchString) {
      this.searchCriteria = searchString
    },
    applySearchFilter(doc) {
      console.log('in applySearchFilter')
      // If no search criteria return everything
      if (this.searchCriteria === null) {
        return true
      }

      if (doc.filename.toLowerCase().includes(this.searchCriteria.toLowerCase())) {
        return true
      }
      return false
    }
  },
  computed: {
    filteredDocuments() {
      console.log('in computed')
      return this.documents
        .filter(this.applySearchFilter)
    }
  },
  components: {
    search: {
      template: '#child-template',
      props: {
        searchCriteria: {
          type: String,
          required: true
        }
      },
      computed: {
        search: {
          get() {
            return this.searchCriteria;
          },
          set(value) {
            this.$emit('search-string', value);
          }
        }
      }
    }
  }
});
<link href="https://unpkg.com/quasar-extras@latest/material-icons/material-icons.css" rel="stylesheet"/>
<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
<link rel="stylesheet" type="text/css" href="https://unpkg.com/quasar-framework@latest/dist/umd/quasar.mat.min.css">
<script src="https://unpkg.com/quasar-framework@latest/dist/umd/quasar.mat.umd.min.js"></script>
<div id="app">
  <search :search-criteria="searchCriteria" @search-string="updatedSearchString"></search>
  <div v-for="(doc, index) in filteredDocuments" v-bind:key="index">
    <div>{{doc.filename}}</div>
  </div>
</div>

<template id="child-template">
  <div>
    <q-search v-model="search" placeholder="Search" />
  </div>
</template>
👤Roy J

Leave a comment