欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Vue脚手架 之 input自动获取焦点 全局设置自定义指令

程序员文章站 2022-03-30 13:09:11
...
import Vue from 'vue'
// 调用时直接在input或textarea标签上添加v-focus指令
Vue.directive('focus', {  //全局注册自定义指令
  inserted (el) {
    if (['INPUT', 'TEXTAREA'].indexOf(el.tagName) !== -1) {
      el.focus()
    } else {
      let node = el.querySelector('input')
      if (node) {
        node.focus()
        return
      }
      node = el.querySelector('textarea')
      if (node) {
        node.focus()
        return
      }
      throw new Error('请把v-focus指令用到input或textarea上')
    }
  }
})

直接放到main.js使用就可以