I have a QR code creating page. I want my QR codes to be created dynamically by user input. But I don’t want to instantly create a QR code. I want to wait my user to finish writing then after one second i will generate the QR code. So I have a template like below:
JavaScript
x
5
1
<div class="app">
2
<qrcode-vue :value="genaratedQrCode"></qrcode-vue>
3
<input type="text" v-model="qrCodeInput" />
4
</div>
5
And my script:
JavaScript
1
30
30
1
import QrcodeVue from 'qrcode.vue';
2
3
export default {
4
data() {
5
return {
6
genaratedQrCode: '',
7
qrCodeInput: '',
8
isInputFunctionRunning: false
9
}
10
},
11
watch: {
12
async qrCodeInput() {
13
if (this.isInputFunctionRunning) {
14
return;
15
}
16
17
this.isInputFunctionRunning = true;
18
19
await new Promise(r => setTimeout(r, 1000));
20
21
this.genaratedQrCode = this.qrCodeInput;
22
23
this.isInputFunctionRunning = false;
24
}
25
}
26
components: {
27
QrcodeVue,
28
},
29
}
30
Apparently the code is not working. It generated the QR code every one seconds. What I want is waiting till user finished, then updating after 1 seconds.
Advertisement
Answer
You have to use .lazy
modifier :
JavaScript
1
2
1
<input type="text" v-model.lazy="qrCodeInput" />
2
If you want to wait some delay try this :
JavaScript
1
42
42
1
import QrcodeVue from 'qrcode.vue';
2
3
function debounce (fn, delay) {
4
var timeoutID = null
5
return function () {
6
clearTimeout(timeoutID)
7
var args = arguments
8
var that = this
9
timeoutID = setTimeout(function () {
10
fn.apply(that, args)
11
}, delay)
12
}
13
}
14
15
16
17
export default {
18
data() {
19
return {
20
genaratedQrCode: '',
21
qrCodeInput: '',
22
isInputFunctionRunning: false
23
}
24
},
25
watch: {
26
qrCodeInput:debounce(function() {
27
if (this.isInputFunctionRunning) {
28
return;
29
}
30
31
this.isInputFunctionRunning = true;
32
33
this.genaratedQrCode = this.qrCodeInput;
34
35
this.isInputFunctionRunning = false;
36
},1000)
37
}
38
components: {
39
QrcodeVue,
40
},
41
}
42
This is based on this answer;