行内input框编辑,解决blur与click冲突问题

346 阅读1分钟

思路

双击鼠标,显示input框,并获取焦点, 点击保存按钮或enter进行保存 若保存失败,重新获取焦点 总结事件顺序应为:mousedown->(other)blur->mouseup->click

<!-- 任务优先级 -->
  <template #priority="{ row }">
    <div v-if="row.toggle">
      <u-input-number
        class="priority-input"
        :auto-focus="true"
        v-model="row.priority"
        placeholder="[1, 100]"
        style="width: 60px"
        :default-value="0"
        :min="0"
        :step="1"
        :max="100"
        @blur="handleRecoverPriority(row)"
        @enter="handlePriority(row)"
      />
      <u-tooltip title="保存">
        <u-button
          type="text"
          icon="save"
          class="m-r-1 action-button"
          @mousedown="handlePriority(row)"
        />
      </u-tooltip>
    </div>
    <div v-else class="table-priority" @dblclick="handleEditPriority(row)">
      <u-button type="text">
        {{ row.priority }}
      </u-button>
    </div>
  </template>
// 保存编辑优先级
const togglePriority = row => {
  // 保存
  if (row.toggle) {
    row.priorityDisabled = true; // 禁用编辑
    // 发送请求
    editPriorityApi({
      id: row.id,
      priority: row.priority
    })
      .then(data => {
        if (data) {
          row.toggle = !row.toggle;
          row.priorityHis = row.priority;
          message.success('优先级修改成功');
        } else {
          message.error('优先级修改失败');
        }
      })
      .catch(err => {
        message.error(err);
        // 重新获取焦点
        document.querySelectorAll('.priority-input').forEach(v => {
          v.getElementsByTagName('input')[0].focus();
        });
      })
      .finally(() => {
        row.priorityDisabled = false; // 启用
      });
  } else {
    //  编辑
    row.toggle = !row.toggle;
  }
};
// 节流函数
const debouncePriority = debounce(togglePriority, 300, true);
// 保存、编辑
const handlePriority = row => {
  if (row.priority < 0 || row.priority > 100) {
    message.error('优先级范围是[0,100]!');
    return;
  }
  if (!/^[+]{0,1}(\d+)$/.test(row.priority)) {
    message.error('优先级仅支持输入正整数!');
    return;
  }
  // 节流-300ms内允许执行一次
  debouncePriority(row);
};

/**
 * @description:编辑优先级
 * @param {*} row
 * @return {*}
 */
const handleEditPriority = row => {
  row.priorityHis = row.priority;
  row.toggle = true;
};

/**
 * @description:失去焦点,恢复原始优先级
 * @param {*} row
 * @return {*}
 */
const handleRecoverPriority = row => {
  // 所以总结事件顺序应为:mousedown->(other)blur->mouseup->click
  if (!row.priorityDisabled) {
    // 保存时,不允许执行失去焦点操作
    row.priority = row.priorityHis;
    row.toggle = false;
  } else {
    console.log('保存编辑和失去焦点,同时执行时,优先执行保存(mousedown)操作');
  }
};