我在输入中使用vue @keyup
,这使用了axios
调用的方法:
<template>
<div>
<input type="text" placeholder="Where are you from?" v-model="from" @keyup="getPlace">
<ul>
<li v-for="place in places">{{ place.name }}<li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
places: [],
from: ''
}
},
methods() {
if(this.from.length <= 3) { this.places = []; return; }
getPlace() {
axios.get('/places?name='+this.from).then((res)=>{
this.places = [];
for(var i = 0; i<res.data.length; i++) {
this.places.push(res.data[i]);
}
}).catch((err)=>{console.log(err)});
}
}
};
</script>
现在这有效,但是它有一个大问题,每次调用都会更新位置数组,但是已经晚了,因此调用了该方法,并且数组已返回到[],但是在响应返回之后,它正在为该数组填充每个快捷键(如果您快速键入)...我正在从jquery切换到这个,而我从来没有遇到过这个问题:O
答案 0 :(得分:2)
这不会回答“如何中止方法”,但是您可以为示例使用另一种方法:获取开头的所有位置(mounted()
)并根据前端的输入对其进行过滤通过使用计算属性。
var app = new Vue({
el: '#app',
data() {
return {
places: [],
from: ''
}
},
mounted() {
this.getPlaces();
},
computed: {
placesList() {
let result = []
let places = this.places
let from = this.from
if (from !== '') {
result = this.places.filter(element => {
return element.name.toLowerCase().includes(from.toLowerCase())
})
} else {
result = places
}
return result
}
},
methods: {
getPlaces() {
// axios call..
this.places = [{
id: 1,
name: "Germany"
}, {
id: 2,
name: "USA"
}, {
id: 3,
name: "Spain"
}]
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
<div id="app">
<input type="text" placeholder="Where are you from?" v-model="from">
<br /> input text: {{ from }}
<hr>
<ul>
<li v-for="place in placesList" :key="place.id">
{{ place.name }}
</li>
</ul>
</div>