我们的需求中有这么两项:
1、当el-input出现的时候自动获取焦点,并且让里面的内容全选;
2、但是在鼠标按下时候,取消对内容全选。让用户可以自己勾选;
第一个需求其实比较简单, 就是当页面出现的时候,让el-input获取焦点,并且在获取焦点的时候,触发input的获取焦点事件,在获取焦点事件中自动全选内容;
第二个需求,需要在el-input中添加mousedown事件,但是如果直接使用@mousedown会导致el-input不能触发鼠标按下的事件。需要使用`@mousedown.nactive`
还有一个是取消文字的全选,我去网上找,都是让其中的内容全选, 取消全选是没有一个unselect方法的。直到看到了input的方法中还有一个这样的setSelectionRange
方法。可以使用这个方法让内容取消选中。(注意:这里是鼠标按下的时候取消全选,如果是鼠标按下并且抬起就不用使用这个方法了,因为input会自动的取消全选)
HTMLInputElement.setSelectionRange
方法用于设定<input> 或 <textarea> 元素中当前选中文本的起始和结束位置。
<div class="cpoyAddressDom" v-show="isShowCopyAddressDom">
<el-input
v-model="routerAddress"
ref="routerAddressInput"
@focus="routerAddressFocus"
@blur="routerAddressBlur"
@keyup.enter="enterKeyup"
@mousedown.nactive="inputMouseDown"
/>
</div>
methods: {
// 输入框鼠标按下,直接是去焦点
inputMouseDown(e){
e.currentTarget.setSelectionRange(0,0);
},
// 点击地址栏,让输入框显示,并且获取焦点
showCopyAddressDom() {
this.isShowCopyAddressDom = true;
this.$refs.routerAddressInput.focus();
},
// 获取焦点的时候,自动选中
routerAddressFocus(e) {
e.currentTarget.select();
},
// 失去焦点,让输入框隐藏
routerAddressBlur() {
this.isShowCopyAddressDom = false;
this.getRouterAddress();
},
}