当前位置:网站首页>自定义指令,获取焦点
自定义指令,获取焦点
2022-08-01 20:01:00 【kilito_01】
// 对Vue的全局指令, 进行封装
// 封装中间件函数插件
const directiveObj = {
install (Vue) {
Vue.directive('focus', {
// el代表指令所在标签
// 指令所在标签, 被插入到真实DOM时才触发, 如果标签用display:none隐藏再出现, 不会在触发inserted的
inserted (el) {
// 指令所在van-search组件
// 组件根标签是div, input在内部
// 以上都是原生标签对象
// 搜索页面 el是div
// 文章评论 el是textarea
// 以后el还可能是input呢
// 知识点: 原生DOM.nodeName 拿到标签名字 (注意: 大写的字符串)
if (el.nodeName === 'TEXTAREA' || el.nodeName === 'INPUT') {
el.focus()
} else {
// el本身不是输入框, 尝试往里获取一下
setTimeout(() => {
const theInput = el.querySelector('input')
const theTextArea = el.querySelector('textarea')
// 判断: 不一定能获取得到, 需要加判断, 有值了, 再执行.focus()才不报错
if (theInput) theInput.focus()
if (theTextArea) theTextArea.focus()
})
}
},
update (el) {
// 指令所在标签, 被更新时触发
if (el.nodeName === 'TEXTAREA' || el.nodeName === 'INPUT') {
el.focus()
} else {
// el本身不是输入框, 尝试往里获取一下
setTimeout(() => {
const theInput = el.querySelector('input')
const theTextArea = el.querySelector('textarea')
// 判断: 不一定能获取得到, 需要加判断, 有值了, 再执行.focus()才不报错
if (theInput) theInput.focus()
if (theTextArea) theTextArea.focus()
})
}
}
})
}
}
export default directiveObj
在main。js中全局注册就好了
import directiveObj from ‘./utils/directive’
Vue.use(directiveObj)
边栏推荐
猜你喜欢
随机推荐
数字孪生北京故宫,元宇宙推进旅游业进程
【节能学院】安科瑞餐饮油烟监测云平台助力大气污染攻坚战
nacos installation and configuration
[Personal Work] Remember - Serial Logging Tool
18、分布式配置中心nacos
不同的操作加不同的锁详解
Pytorch模型训练实用教程学习笔记:二、模型的构建
【多任务模型】Progressive Layered Extraction: A Novel Multi-Task Learning Model for Personalized(RecSys‘20)
17. Load balancing
C语言实现-直接插入排序(带图详解)
第55章 业务逻辑之订单、支付实体定义
给定中序遍历和另外一种遍历方法确定一棵二叉树
【无标题】
【软考软件评测师】基于规则说明的测试技术下篇
工作5年,测试用例都设计不好?来看看大神的用例设计总结
有用的网站
【节能学院】智能操控装置在高压开关柜的应用
数据库系统原理与应用教程(072)—— MySQL 练习题:操作题 121-130(十六):综合练习
An implementation of an ordered doubly linked list.
Pytorch模型训练实用教程学习笔记:一、数据加载和transforms方法总结









