【发布时间】:2017-07-20 11:22:28
【问题描述】:
我在输入从 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>
helpers/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: undefined is not an object (evaluate 'this.searchTerm')'。
如果我对 foodData 数组进行硬编码,一切都会完美运行。
我是否误解了什么和/或我做错了什么?
【问题讨论】:
-
两个问题: 1. 您是否尝试过修复
filteredItems中的this引用? 2.你在哪里/如何设置searchTerm?我在您的模板中没有看到它。 -
将丢失的 添加到我忘记在此处添加的 HTML 中。您能解释一下修复这些引用的含义吗?
-
伯特说了什么;)
标签: javascript node.js ajax vue.js