Vue uses the input component, loses focus and presses the Enter key to cause the same method to be executed twice

need:

Use the el-input in element-ui as the input box of the page. When the input box loses focus and the user presses Enter, both trigger the same search data event.

1. Problems

<template>
 <el-input v-model="val" @blur="searchData"  @keyup.enter.native="searchData"></el-input>
</template>
 
<script>
 export default {
    data() {
      return {
        val: ''
       }
    },
    methods: {
       searchData() {... //搜索操作}
    }
 }
</script>

problem appear:

If the el-input is still in the focused state, after pressing enter to trigger the search event, when the el-input loses focus, it will trigger another search event.

Two, the solution

At this time, you need to make the el-input lose focus after pressing enter, and you need to use $event at this time.

<template>
 <el-input v-model="val" @blur="searchData"  @keyup.enter.native="$event.target.blur()"></el-input>
</template>
 
<script>
 export default {
    data() {
      return {
        val: ''
       }
    },
    methods: {
       searchData() {... //搜索操作}
    }
 }
</script>

In this way, whether you lose focus or press Enter, the method will only be called once to avoid problems

Guess you like

Origin blog.csdn.net/weixin_43743175/article/details/127758892