Implement the Vue button (button) to bind the carriage return (enter) event

Tip: After the article is written, the table of contents can be automatically generated. How to generate it can refer to the help document on the right


foreword

Sometimes there is such a requirement in the project. When the user clicks a certain function dialog box (for example: delete, unbind), when the user clicks OK, it is hoped that the enter key will complete the operation instead of clicking the mouse. Here is the method I use


1. Page display

As shown in the figure, delete is triggered after clicking OK or pressing the Enter key
insert image description here

2. Implementation steps

1. Add an input box between the Cancel and OK buttons of the delete dialog box

code show as below:

<!-- 删除弹窗 -->
    <el-dialog
      :append-to-body="true"
      :title="deleteTitle"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="30%"
    >
      <span class="rent-span">{
    
    {
    
     this.dialogText1 }}</span>
      <span class="rent-span2">{
    
    {
    
     this.dialogText2 }}</span>
      <span class="rent-span">{
    
    {
    
     this.dialogText3 }}</span>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogConfirm('cancel')">取 消</el-button>
        
        //在删除对话框的取消与确定按钮之间添加input输入框
        <input
          type="text"
          ref="inputdata"
          class="hiddenIpt"
          @keyup.enter="dialogConfirm('confirm')"
        />
        
        <el-button
          type="primary"
          @click="dialogConfirm('confirm')"
        >确 定</el-button>
      </span>
    </el-dialog>

2. Write a listener to automatically focus on the input box when the pop-up window is opened (inputdata is bound with ref on the input).

code show as below:

watch: {
    
    
    dialogVisible() {
    
    
      if (this.dialogVisible) {
    
    
        //this.$refs.inputdata.focus(); 错误写法

        this.$nextTick(() => {
    
    
          //正确写法

          this.$refs.inputdata.focus();
        });
      }
    }
  },

3. Hide the input box

code show as below:

<style lang="scss" scoped>
.hiddenIpt {
    
    
  width: 1px;
  opacity: 0;
}
</style>

Summarize

In summary, there are roughly three steps:

  1. Add an input box between the Cancel and OK buttons of the delete dialog
  2. Write a listener to automatically focus the input box when the pop-up window is opened ( inputdata is bound with ref on the input)
  3. hide input box

related articles

An article teaches you to implement VUE multiple DIV, button binding carriage return event

Guess you like

Origin blog.csdn.net/daishu_shu/article/details/128548389