当前位置:   article > 正文

Error in directive fofo inserted hook: “TypeError: Cannot read properties of null (reading ‘focus‘)_cannot read properties of null (reading 'focus')

cannot read properties of null (reading 'focus')

vue.runtime.esm.js?c320:574 [Vue warn]: Error in directive fofo inserted hook: “TypeError: Cannot read properties of null (reading ‘focus’)”
在这里插入图片描述

本身已经是textarea了不能再获取input了,所以获取了空

解决办法:

// 插件对象(必须有install方法, 才可以注入到Vue.use中)
export default {
  install() {
    Vue.directive('fofo', {
      // el表示指令所在标签
      // 指令所在标签, 被插入到真实DOM时才触发, 如果标签用display:none隐藏再出现, 不会在触发inserted的
      inserted(el) {
        // 指令在van-search组件身上, 获取的是组件根标签div, 而input在标签内
        // 以上都是原生标签对象
        // 搜索页面 el是div
        // const theInput = el.querySelector('input')
        // theInput.focus()
        // 文章评论 el是textarea
        // 以后el还可能是input呢
        // 知识点: 原生DOM.nodeName 拿到标签名字 (注意: 大写的字符串)
        if (el.nodeName === 'TEXTAREA' || el.nodeName === 'INPUT') {
          el.focus()
        } else {
          // el本身不是输入框, 尝试往里获取一下
          const theInput = el.querySelector('input')
          const theTextArea = el.querySelector('textarea')
          // 判断: 不一定能获取得到, 需要加判断, 有值了, 再执行.focus()才不报错
          if (theInput) theInput.focus()
          if (theTextArea) theTextArea.focus()
        }
      }
    })
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号