基于vue框架,vant组件库,移动端的搜索框实现自动聚焦,使用自定义指令

2022-09-15 10:26:30

通过全局自定义(directives)指令来实现搜索框的自动聚焦

import Vuefrom'vue'// 插件对象(必须有install方法, 才可以注入到Vue.use中)exportdefault{install(){
    Vue.directive('fofo',{inserted(el){fn(el)},update(el){fn(el)}})}}functionfn(el){if(el.nodeName==='INPUT'|| el.nodeName==='TEXTAREA'){// 如果直接是input标签/textarea标签
    el.focus()}else{// 指令在van-search组件身上, 获取的是组件根标签div, 而input在标签内const inp= el.querySelector('input')const textArea= el.querySelector('textarea')// 如果找到了if(inp|| textArea){
      inp&& inp.focus()
      textArea&& textArea.focus()}else{// 本身也不是, 子标签里也没有
      console.error('请把v-fofo用在输入框标签上')}}}
  • 作者:新时代农民工Top
  • 原文链接:https://blog.csdn.net/web00_11/article/details/119424379
    更新时间:2022-09-15 10:26:30