自定义指令,获取焦点

// 对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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值