Computed function in Vue not defined

I using a computed object to conditionally return a list item. But, I get "ReferenceError: matchingEmployees is not defined" even though I defined it in the computed object. What am I missing? I checked for spelling errors and the reference to matchingEmployees in the directive matches the computed function. Thank you. You can see the entire code on this codepen.

new Vue({
  el: '#app',
  template:
  `<div>
    <h1>Vue.js Application</h1>
    Search: <input v-model="searchStr" type="text" placeholder="Search Employee...">
    <h2>All employees are listed below</h2>

    <p v-for="employee in matchingEmployees">
      {{ employee }}
    </p>
  </div>
  `,
  data: {
    searchStr:'',
    employees: [
      'Alex Han', 
      'Ali Usman', 
      'Peter Parker', 
      'John Lee', 
      'Eva Holmes'
    ],
     computed: {
    matchingEmployees: function () {
      return this.employees.filter((user)=> {
        if (this.searchStr == ''){
          return true;
        } else {
          return user.includes(this.searchStr)
        }
      })
      }
     }
  }
})

#1 Answers

computed property must be outside the data option, the data option must be a function that returns an object :

new Vue({
  el: "#app",

  data() {
    return {
      searchStr: "",
      employees: [
        "Alex Han",
        "Ali Usman",
        "Peter Parker",
        "John Lee",
        "Eva Holmes"
      ]
    };
  },
  computed: {
    matchingEmployees: function () {
      return this.employees.filter((user) => {
        if (this.searchStr == "") {
          return true;
        } else {
          return user.includes(this.searchStr);
        }
      });
    }
  }
});

However adding template as an option is working I recommend to move to the html section in order to separate the content from the logic :

<div id="app">
  <div>
    <h1>Vue.js Application</h1>
    Search: <input v-model="searchStr" type="text" placeholder="Search Employee...">
    <h2>All employees are listed below</h2>

    <p v-for="employee in matchingEmployees">
      {{ employee }}
    </p>
  </div>

</div>

Comments