vue.js keyup, keydown 事件落后一字符 [英] vue.js keyup, keydown events one character behind
问题描述
我正在使用调用 javascript 函数的 keydown/keyup 事件,该函数将输入框的值(以及事件的 currentTarget 字段的值)打印到控制台,我注意到它是一个字符.例如,如果我在输入框中输入 hello,我只会在控制台中看到 hell,直到我按下另一个键,然后我看到 hello>,尽管此时我已经输入了 hello1.为什么是这样?周围还有吗?
这是 HTML:
还有 JS:
queryForKeywords: function(event) {var self = this;如果(this.keywords.length > 2){console.log("关键字值:" + this.keywords);console.log("事件值:" + event.currentTarget.value);}
因为你依赖输入的 v-model
来更新 keywords
属性,取值直到 Vue 组件重新渲染后才更新.
您可以在传递给 keywords 的更新值>this.$nextTick
就像这个例子:
new Vue({el: '#app',数据() {返回{关键字:''}},方法: {查询关键字:函数(事件){this.$nextTick(() => {如果(this.keywords.length > 2){console.log("关键字值:" + this.keywords);}});}}})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script><div id="应用程序"><input type="text" class="form__field" v-model="keywords" v-on:keyup.enter="queryForKeywords" v-on:keydown="queryForKeywords">
I'm using the keydown/keyup events which call a javascript function that prints the value of input box to the console (and also the value of the currentTarget field of the event), and I am noticing it is a character late. For example, if I type hello into the input box, I only see hell in the console, until I press another key and then I see hello, even though by this point I've typed hello1. Why is this? And is there anyway around it?
Here's the HTML:
<input type="text" class="form__field" v-model="keywords" v-on:keyup.enter="queryForKeywords" v-on:keydown="queryForKeywords">
And the JS:
queryForKeywords: function(event) {
var self = this;
if (this.keywords.length > 2) {
console.log("keywords value: " + this.keywords);
console.log("event value: " + event.currentTarget.value);
}
Because you are depending on the input's v-model
to update the keywords
property, the value won't update until the Vue component has re-rendered.
You can access the updated value of keywords
in a callback passed to this.$nextTick
like in this example:
new Vue({
el: '#app',
data() {
return { keywords: '' }
},
methods: {
queryForKeywords: function(event) {
this.$nextTick(() => {
if (this.keywords.length > 2) {
console.log("keywords value: " + this.keywords);
}
});
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app">
<input type="text" class="form__field" v-model="keywords" v-on:keyup.enter="queryForKeywords" v-on:keydown="queryForKeywords">
</div>
这篇关于vue.js keyup, keydown 事件落后一字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!