优化_自动聚焦问题

目标:我们想实现,网页一加载input框自动聚焦

在utils文件下创建  directive.js封装中间件

固定格式:

import Vue from 'vue'
// 封装中间价函数插件
const directiveObj = {
  install (vue) {
     //实现体
    
  }
}

export default directiveObj
import Vue from 'vue'
// 封装中间价函数插件
const directiveObj = {
  // 只有第一次出现是插入到真实DOM, 触发inserted方法
  // 以后初选是css层面的显示出现(eg:css的display:none), 不会触发inserted方法
// 插件对象(必须有install方法, 才可以注入到Vue.use中)
  install (vue) {
    // 自定义全局指令---对input可以自动聚焦
    Vue.directive('fofo', {
      // el参数为被绑定fofo指令的dom节点
      inserted (el) {
        fn(el)
      },
      update (el) {
        fn(el)
      }
    })
  }
  // 给自定义指令添加update方法, 指定所在DOM更新时执行
}
function fn (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用在输入框标签上')
    }
  }
}
export default directiveObj

使用:

<van-field
      v-fofo
      v-model.trim="message"
      rows="2"
      autosize
      type="textarea"
      maxlength="10"
      placeholder="请输入昵称"
      show-word-limit
    />

猜你喜欢

转载自blog.csdn.net/m0_65812066/article/details/128634349
今日推荐