vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > vue点击按钮input保持聚焦状态

vue实现点击按钮input保持聚焦状态的示例代码

作者:雅痞yuppie

这篇文章主要介绍了vue实现点击按钮input保持聚焦状态,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

主要功能:

以下是代码版本:

<template>
  <div class="input-container">
    <el-input
      v-model="input"
      style="width: 240px"
      placeholder="Please input"
      ref="inputRef"
      class="input-ref"
      @focus="handleFocus"
    />
    <el-button 
      class="input-btn" 
      @click.stop="toggleDialog" 
      :disabled="!isFocused"
      :type="showDialog ? 'primary' : ''"
    >
      停顿 {{ isFocused ? 'ON' : 'OFF' }}
    </el-button>
    <transition name="fade">
      <div v-if="showDialog" class="dialog-wrapper" @click.stop>
        <dl class="dialog-content">
          <dt>插入内容</dt>
          <dd @click="closeDialog" style="cursor: pointer">插入btn</dd>
        </dl>
      </div>
    </transition>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
const showDialog = ref(false);
const input = ref("");
const inputRef = ref<HTMLInputElement>();
const isFocused = ref(false);
const handleDocumentClick = (e: MouseEvent) => {
  const target = e.target as HTMLElement;
  const clickedInside = target.closest(".input-container");
  if (!clickedInside && isFocused.value) {
    closeDialog();
  }
};
onMounted(() => {
  document.addEventListener("click", handleDocumentClick);
});
onBeforeUnmount(() => {
  document.removeEventListener("click", handleDocumentClick);
});
function closeDialog() {
  showDialog.value = false;
  if (inputRef.value) {
    inputRef.value.blur();
  }
  isFocused.value = false;
}
function handleFocus() {
  isFocused.value = true;
}
function toggleDialog() {
  showDialog.value = !showDialog.value;
  if (inputRef.value) {
    inputRef.value.focus();
  }
}
</script>
<style scoped>
.input-container {
  position: relative;
  display: inline-block;
}
.dialog-wrapper {
  position: absolute;
  top: 100%;
  left: 0;
  margin-top: 8px;
  padding: 12px;
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  z-index: 2000;
}
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.2s;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>

主要优点:

更好的结构

安全的实现

用户体验

代码组织

DOM 检查优化

到此这篇关于vue实现点击按钮input保持聚焦状态的文章就介绍到这了,更多相关vue实现点击按钮input保持聚焦状态内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文