为什么给input框绑定keyup keydown 或者keypress事件,显示出来的内容总是滞后呢?

来源:2-8 使用 Composition API 开发TodoList(2)

慕码人1556588

2021-05-11 00:02:27

相关代码:

问题描述:为什么给input框绑定keyup keydown 或者keypress事件,显示出来的内容总是滞后呢?我怎么感觉我们没有学过input事件

相关截图:

http://img.mukewang.com/climg/609958cc091c599404380097.jpg

相关代码:

​const app = Vue.createApp({
setup(){
const {ref,reactive}=Vue;
const inputValue=ref('请输入内容');
const list=reactive([])
const handleAdd=()=>{
list.push(inputValue.value);
inputValue.value=''
};
const handleInput=(e)=>{
console.log(e.target.value);
inputValue.value=e.target.value;
};
const handleInputFocus=()=>{
inputValue.value=''
};
return{
inputValue,
list,
handleAdd,
handleInput,
handleInputFocus
}
},
template: `
<input :value='inputValue' @keypress='handleInput' @focus='handleInputFocus' />
<button @click='handleAdd'>增加</button>{{inputValue}}
<div v-for='(value,index) in list' :key='index'>{{value}}</div>
`
});

const vm= app.mount('#root');


写回答

1回答

好帮手慕久久

2021-05-11

同学你好,解答如下:

1、input事件是输入框内容正在改变时触发,在如下课程中讲过,同学可以回顾一下:

https://class.imooc.com/lesson/1626#mid=38882(20分48秒)

2、给input绑定keyup事件,内容显示不会延后:

http://img.mukewang.com/climg/6099e9c7094591e810510775.jpg

同学可以再测试一下。

3、keydown和keypress事件,内容会滞后显示。这样因为二者都是“按键被按下时”触发,而“内容”是在按键被抬起时才会显示在input上,即“按键按下时”最新的内容还没有输入到input内,因此获取到的内容是上一次的,有滞后:

http://img.mukewang.com/climg/6099ea6b0981907807790609.jpg

http://img.mukewang.com/climg/6099eaa6094dc90b07070597.jpg

祝学习愉快!​

0

0 学习 · 15276 问题

查看课程