Normally, when user types some value in input field the value is automatically updated in a model. What I need is to prevent value from being updated automatically for some period of time. In my app I draw a grid on canvas. User types length and width in input fields. I want to trigger drawing a grid when width
is set by user, not earlier (I use watch
for that reason). The issue is that when user types width e.g. 57 then it first draws a grid of width=5 and right after that the width=57. It means I finally have 2 grids. The reason is that Vue responds immediately to what user types in input.
I tried to get around it somehow using v-model.lazy
but it doesn't work. I also tried to use setTimeout()
but it doesn't seem to work at all. I commented out this chunk of code in my reproducible example:
function draw() {
for (var j=0; j<rows; j ) {
for (var i=0; i<cols; i ) {
tile = new Rectangle({width:size, height:size, borderColor:"#a8a8a8", borderWidth:0.2})
.centerReg(tiles)
.loc(size/2 i*(size), size/2 j*(size));
}
}
}
setTimeout(draw, 3000) // here I wait 3 sec after user inputs value in this field
Generally speaking - I want the program to wait until user inputs lenght and width and once values are input then draw a grid.
Here is a reproducible example: https://codesandbox.io/s/vue-2-playground-vuex-drag-and-snap-to-tiles-un6984?file=/src/components/ZimModel.vue
CodePudding user response:
Your problem could be solved if whatever function that makes the grid gets triggered with a @blur
attribute on the input field (which triggers when a user leaves the input field)
Or by adding the @input
attribute which triggers a function that calls a setTimeOut (every time clears the said timeOut before setting it, to avoid multiple code executions), and if the timeOut finishes before getting cleared by another keystroke, your function gets executed.