方法1:在需要触发聚焦的方法里写上,el-input上绑定 ref="autoFocus"
this.$nextTick((_) => {
this.$refs.autoFocus.focus();
})
注意:如果el-input是在el-popover中使用的, 那这个触发的方法必须写在 el-popover 的 show 事件上才能生效,如下图所示(ps: 这段代码的背景是产品反馈el-select的搜索有人不会用,所以要我自己写个假的选择器实现搜索功能,哎)
(后续:单元详情里有两个这样的搜索框,使用起来会有偶发性的页面卡死,我就悄悄把这个自动聚焦功能删掉了...)
<el-popover placement="bottom-start" width="230" trigger="click"
@show="handleInputFocus">
<el-input v-model="filterPlanName"
ref="autoFocus"
placeholder="请输入计划名称搜索"
@keyup.enter.native="$event.target.blur()"
@blur="handleFilterPlanName"
style="width: 100%; padding: 4px"></el-input>
<ul class="thin-scrollbar f12" style="padding:4px 10px;max-height: 300px; overflow-y: scroll">
<li class="flex flex-between flex-align-center"
v-for="item in campaignList"
:key="item.campaignId"
@click="planChange(item)"
:class="{ active: item.campaignId == params.campaignId }">
<span class="text-overflow flex1 pointer"
style="line-height: 26px"
:title="item.campaignName">
{{ item.campaignName }}
</span>
<i class="el-icon-check color-theme" v-show="item.campaignId == params.campaignId"></i>
</li>
</ul>
<span slot="reference" class="pointer flex flex-align-center" style="outline: none">
<p class="planName-box f12">{{ campaignInfo.campaignName }}</p>
<span class="el-icon-arrow-down" style="margin-left: -20px"></span>
</span>
</el-popover>
handleInputFocus() {
this.$nextTick((_) => {
this.$refs.autoFocus&&this.$refs.autoFocus.focus();
})
},
planChange(item) {
document.getElementsByTagName('body')[0].click(); //失焦关闭弹框
if (item.campaignId == this.params.campaignId) {
return;
}
this.params.campaignId = item.campaignId
this.handleChangeCampaign()
},
实现效果如图所示
方法2:指令写法,el-input上写上指令 v-focus
directives: {
focus: {
inserted: function (el) {
el.querySelector("input").focus()
}
}
},
这个是在组件内写的,如果需要聚焦的地方多,可以把这个指令写成全局指令,方便使用