vue中 input框 清除按钮的显示与隐藏

<input v-model="name" class="input step2-cont-ipt" required placeholder="请输入姓名" >
<a class="clear" @click="clear1();return false;"></a>
methods: {
        clear1(){
            if(this.name){
                this.name = '';
            }
        }
    }
.clear { 
                    display: none; 
                    position: absolute; 
                    width: 30px; 
                    height: 30px;
                    right: 2%;
                    top: 50%;
                    transform: translate(-2%,-50%);
                    background: url('../../assets/images/clear.png');
                    background-size:100% 100%;
                }
                .input::-ms-clear { display: none; }
                .input:valid + .clear { display: inline; }

 

### 带有清除按钮的搜索组件 为了实现在 Vue 中创建一个带有清除按钮的搜索组件,可以利用 `Element Plus` 提供的基础输入框组件并对其进行扩展。通过监听用户的交互行为来控制显示隐藏清除图标,并在点击该图标时清空输入框内容。 #### 组件模板结构设计 ```html <template> <el-input v-model="searchText" placeholder="请输入关键字..." class="search-box" @input="handleInput" @focus="showClearButton = true" @blur="onBlurHandler"> <template #suffix> <i v-if="showClearButton && searchText.length > 0" class="el-icon-close clear-button" @click.stop="clearSearch"></i> </template> </el-input> </template> <script setup lang="ts"> import { ref, watch } from &#39;vue&#39;; const props = defineProps({ modelValue: { type: String, default: &#39;&#39; } }); // 定义emit用于父级更新v-model绑定值 const emit = defineEmits([&#39;update:modelValue&#39;]); let searchText = ref(props.modelValue); watch(() => props.modelValue, (newValue) => { searchText.value = newValue; }); function handleInput(value:string){ emit(&#39;update:modelValue&#39;, value); } let showClearButton = ref(false); function onBlurHandler(){ setTimeout(()=>{ if(!document.activeElement.classList.contains(&#39;search-box&#39;)){ showClearButton.value=false; } },100); } function clearSearch(){ searchText.value=&#39;&#39;; emit(&#39;update:modelValue&#39;,&#39;&#39;); showClearButton.value=false; } </script> <style scoped> .clear-button:hover{ cursor:pointer; color:red; } .search-box .el-input__inner:focus + .el-input__icon .clear-button{ display:block !important; visibility:visible !important; opacity:1!important; transition:.3s ease all; } </style> ``` 此代码片段展示了如何构建一个具有清除功能的搜索[^1]。当用户聚焦于输入框内时会显示出关闭图标的提示,允许他们一键清除当前查询字符串;而一旦失去焦点且无任何文本,则自动隐藏这个辅助操作符。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值