Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

vue.js - 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)
        }
      })
      }
     }
  }
})
question from:https://stackoverflow.com/questions/65858726/computed-function-in-vue-not-defined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...