【问题标题】:Awaiting till user finishes writing to input field in Vue.js等待用户完成写入 Vue.js 中的输入字段
【发布时间】:2020-11-16 23:35:27
【问题描述】:

我有一个二维码创建页面。我希望通过用户输入动态创建我的二维码。但我不想立即创建二维码。我想等待我的用户完成写入,然后一秒钟后我将生成 QR 码。所以我有一个如下模板:

<div class="app">
    <qrcode-vue :value="genaratedQrCode"></qrcode-vue>
    <input type="text" v-model="qrCodeInput" />
</div>

还有我的脚本:

import QrcodeVue from 'qrcode.vue';

export default {
    data() {
        return {
            genaratedQrCode: '',
            qrCodeInput: '',
            isInputFunctionRunning: false
        }
    },
    watch: {
        async qrCodeInput() {
            if (this.isInputFunctionRunning) {
                return;
            }

            this.isInputFunctionRunning = true;

            await new Promise(r => setTimeout(r, 1000));

            this.genaratedQrCode = this.qrCodeInput;

            this.isInputFunctionRunning = false;
        }
    }
    components: {
        QrcodeVue,
    },
}

显然代码不起作用。它每隔一秒生成一个二维码。我想要的是等到用户完成,然后在 1 秒后更新。

【问题讨论】:

  • 浏览器如何判断用户是真的完成了还是只是想输入什么?
  • 这不是思考 :) 它是关于完成“写作”。我不在乎他/她停止写作的原因。我只关心他/她是否停下来。
  • 我的意思是,除非通过一些明确的用户操作,例如关注另一个元素,否则无法检测到这一点。
  • 嗯。我尝试使用 on change 方法。但是异步等待逻辑不起作用。那么这真的是不可能的吗,或者你有什么想法可以通过使用 onchange 来实现吗? watch 方法的作用类似于变化。

标签: javascript vue.js asynchronous vuejs2 vue-component


【解决方案1】:

你必须使用.lazy修饰符:

<input type="text" v-model.lazy="qrCodeInput" />

如果你想等待一些延迟试试这个:

import QrcodeVue from 'qrcode.vue';

function debounce (fn, delay) {
  var timeoutID = null
  return function () {
    clearTimeout(timeoutID)
    var args = arguments
    var that = this
    timeoutID = setTimeout(function () {
      fn.apply(that, args)
    }, delay)
  }
}



export default {
    data() {
        return {
            genaratedQrCode: '',
            qrCodeInput: '',
            isInputFunctionRunning: false
        }
    },
    watch: {
        qrCodeInput:debounce(function() {
            if (this.isInputFunctionRunning) {
                return;
            }

            this.isInputFunctionRunning = true;

            this.genaratedQrCode = this.qrCodeInput;

            this.isInputFunctionRunning = false;
        },1000)
    }
    components: {
        QrcodeVue,
    },
}

这是基于这个answer

【讨论】:

  • 这有点用。但这需要用户将注意力集中在其他地方。
  • 如果 OP 表示用户正在“完成”通过跳格或点击离开输入,这将起作用。
  • @Mansur 请检查第二个建议
猜你喜欢
  • 1970-01-01
  • 2015-09-19
  • 1970-01-01
  • 2013-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
相关资源
最近更新 更多