首页 > 解决方案 > 如何在 Vue 2.6 中 @paste 事件后拦截或清除 v-model 值

问题描述

我对输入字段上的 v-model 和 @paste 事件有疑问。

当我复制某些内容并将其粘贴到输入字段时,它也会在输入字段中显示复制的值。

我想防止这种情况。

我创建了一个简单的 JsFiddle Todo App 来显示问题。

https://jsfiddle.net/k12drcqn/1/

onPaste: function() {
          let clipped = event.clipboardData.getData('text').split("\n");
          clipped.forEach(item => {
             this.todos.push({
                 text: item, done: false
             })
          })
          // is not clearing the v-model: todo
          this.todo = ''
       }

例如,如果您将这样的内容复制到输入字段中:

  1. 任务1
  2. 任务2
  3. 任务3

这些任务将被添加到列表中,但也会显示在输入字段中。是否有可能不在输入字段中显示粘贴的任务?

标签: vue.jsvuejs2

解决方案


onPaste: function() {
   let clipped = event.clipboardData.getData('text').split("\n");
   clipped.forEach(item => {
      this.todos.push({
         text: item, done: false
      })
   })

   // instead of this
   // this.todo = ''

   // make this
   setTimeout(() => {
       this.todo = ''
   }, 0);
}

this.todo = ''我认为同步调用时文本会保留在输入中。


推荐阅读