vue输入框自动聚焦:
注册一个全局自定义指令:
Vue.directive('focus', {
// 当被绑定的元素插入到 DOM 中时
inserted(el) {
dom = el.querySelector('input') || el.querySelector('textarea') || el;
// 防止首次弹窗加载时自动失焦
setTimeout(() => {
dom.focus();
});
},
// 失焦之后监听触发
update(el, binding) {
const { oldValue, value } = binding;
if (!oldValue && value) dom.focus();
},
});
页面中直接使用
<input v-focus>