繁体   English   中英

输入时Vue搜索Ajax响应数组

[英]Vue search Ajax response array while typing

当我输入从Ajax调用获得的文本框时,我试图过滤列表。 问题似乎是在Ajax准备就绪之前应用了过滤器。

HTML:

<input type="text" class="form-control" v-model="searchTerm">
<table>
    <tr v-for="food in filteredItems">
      <td>{{ food.name }}</td>
      <td>{{ food.energy }}</td>
    </tr>
</table>

助手/ index.js:

export default {
  getFoods() {
  return Vue.http.get('http://localhost:3000/foods/allfoods')
         .then((response) => {
             return response.data;
    });
  }
}

Vue组件:

import helpers from '../helpers'
export default {
  name: 'Search',
  mounted() {
    helpers.getFoods().then((response) => {
      this.foodData = response;
    });
  },
  data() {
    return {
      searchTerm: '',
      foodData: [],
    }
  },
  computed: {
    filteredItems() {
      return this.foodData.filter(function(food){return food.name.toLowerCase().indexOf(this.searchTerm.toLowerCase())>=0;});
    }
  }

当我加载页面或开始输入时,我得到

“ TypeError:未定义不是对象(正在评估'this.searchTerm')”。

如果我对foodData数组进行硬编码,那么一切都将完美运行。

我是否误解了某些东西和/或我做错了什么?

在您计算的filter函数的回调中, this并不指向Vue。

computed: {
  filteredItems() {
    return this.foodData.filter(function(food){
      // in this next line, this.searchTerm is likely undefined
      // because "this" is not the Vue
      return food.name.toLowerCase().indexOf(this.searchTerm.toLowerCase()) >= 0;
    });
  }
}

这是因为您正在使用function(food){...}作为回调, this将是包含作用域。 而是使用箭头函数,闭包或bind

computed: {
  filteredItems() {
    return this.foodData.filter(food => {
      // in this next line, this.searchTerm is likely undefined
      // because "this" is not the Vue
      return food.name.toLowerCase().indexOf(this.searchTerm.toLowerCase()) >= 0;
    });
  }
}

 console.clear() const foods = [{ name: "orange", energy: 10 }, { name: "apple", energy: 8 }, { name: "banana", energy: 12 }, { energy: 1000 } ] const Search = { name: 'Search', template: ` <div> <input type="text" class="form-control" v-model="searchTerm"> <table> <tr v-for="food in filteredItems"> <td>{{ food.name }}</td> <td>{{ food.energy }}</td> </tr> </table> </div> `, mounted() { setTimeout(() => this.foodData = foods, 500) }, data() { return { searchTerm: '', foodData: [], } }, computed: { filteredItems() { const searchTerm = this.searchTerm.toLowerCase() return this.foodData .filter(food => food.name && food.name.toLowerCase().includes(searchTerm)) } } } new Vue({ el:"#app", components: {Search} }) 
 <script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script> <div id="app"> <search></search> </div> 

请参见如何访问正确的this回调中

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM