在 Vue.js 中,你可以通过监听 input 框的 blur 事件(失去焦点事件)和 input 事件(内容更改事件)来实现这个功能。你可以使用一个数据属性来存储上一次的值,并在 blur 事件中比较当前值和上一次的值。如果值发生了变化,则发送请求;如果没有变化,则不发送请求。
以下是一个示例代码,展示了如何实现这个功能:
<template>
<div>
<input
type="text"
v-model="inputValue"
@input="handleInput"
@blur="handleBlur"
/>
</div>
</template>
<script>
export default {
data() {
return {
inputValue: '',
lastInputValue: ''
};
},
methods: {
handleInput(event) {
// 更新 lastInputValue 为当前值,以便在 blur 事件中比较
this.lastInputValue = event.target.value;
},
handleBlur() {
// 检查当前值和上一次的值是否不同
if (this.inputValue !== this.lastInputValue) {
// 如果不同,发送请求
this.sendRequest();
// 更新 lastInputValue 为当前值,防止重复请求
this.lastInputValue = this.inputValue;
}
},
sendRequest() {
// 这里写你的接口请求逻辑
console.log('发送请求,输入值为:', this.inputValue);
// 例如使用 axios 发送请求
// axios.post('/your-endpoint', { value: this.inputValue })
// .then(response => {
// console.log('请求成功', response);
// })
// .catch(error => {
// console.error('请求失败', error);
// });
}
}
};
</script>
<style scoped>
/* 你的样式 */
</style>
注意点:
如何input框有初始值(即inputValue有初始值),那么lastInputValue也要有初始值,否则不会生效