自动获取焦点有几种办法:
1.在mounted里面,直接使用document.getElementById('mysearch').focus();
或者 this.$refs.mysearch.focus();
直接使用会报错,找不到元素,必须放在nextTick里面,等渲染dom完成,即可找到元素。
代码
mounted() {
let _this = this;
this.$nextTick(() => {
_this.$refs.mysearch.focus();
});
}
2.使用vue自定义指令
在main.js里面
// 注册一个全局自定义指令 `v-focus`
Vue.directive('focus', {
// 当被绑定的元素插入到 DOM 中时……
inserted(el) {
// 聚焦元素
el.focus();
}
});
在页面使用v-focus
<input
type="text"
autofocus="true"
v-focus
ref="mysearch"
>
3.直接使用h5特性 autofocus="true",但是有个坑,只有第一次进入页面会成功,第二次进入页面会获取不了焦点
注意:如果你的页面使用了keep-alive,那么这些方法都会导致第二次进入页面获取焦点失败
缓存不会重复渲染页面,如果想要每次进入页面都执行,则需要把需要执行的代码放入activated中
activated() {
let _this = this;
this.$nextTick(() => {
(_this.$refs.mysearch as any).focus();
});
}
网友评论