简体   繁体   English

如何防止更新 v-model 输入?

[英]How to prevent update of v-model input?

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).我想在用户设置width时触发绘制网格,而不是更早(出于这个原因,我使用watch )。 The issue is that when user types width eg 57 then it first draws a grid of width=5 and right after that the width=57.问题是,当用户输入宽度,例如 57 时,它首先绘制宽度 = 5 的网格,然后立即绘制宽度 = 57 的网格。 It means I finally have 2 grids.这意味着我终于有 2 个网格。 The reason is that Vue responds immediately to what user types in input.原因是 Vue 会立即响应用户输入的内容。

I tried to get around it somehow using v-model.lazy but it doesn't work.我试图以某种方式使用v-model.lazy解决它,但它不起作用。 I also tried to use setTimeout() but it doesn't seem to work at all.我也尝试使用setTimeout()但它似乎根本不起作用。 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这是一个可重现的示例: https ://codesandbox.io/s/vue-2-playground-vuex-drag-and-snap-to-tiles-un6984?file=/src/components/ZimModel.vue

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)如果使用输入字段上的@blur属性触发了使网格的任何功能(当用户离开输入字段时触发),您的问题就可以解决

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.或者通过添加触发调用 setTimeOut 的函数的@input属性(每次在设置之前清除所述 timeOut,以避免多次代码执行),并且如果 timeOut 在被另一个击键清除之前完成,则您的函数将被执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM