1.首先使用$ref获取要加自动聚焦事件的元素,并添加focus事件
// 自动聚焦方法
onFocus() {
this.$refs.searchPhone.$children[ 0 ].focus();
// 用$refs实在找不到可以用这个
// document.getElementsByClassName( 'van-field__control' )[ 1 ].focus();
},
2.如果有事件用来触发搜索框,那么就将自动聚焦方法写在事件方法中
// 展示弹出层事件
showPopup() {
this.show = true;
this.isFooter = false;
// 因为有一个执行顺序的问题,所以此处需要加一个延迟,可以用$nextTick,也可以用定时器
this.$nextTick( () => {
this.onFocus();
} );
//setTimeout(() => {
//this.onFocus();
//} );
},
若是没有事件触发,需要将聚焦方法调用在mounted中
mounted(){
this.onFoucs();
}