vue 全局创建自定义指令 封装中间件函数插件 实现输入框自动聚焦

下边代码的目的是用自定义指令实现组件中input输入框的自动聚焦

在main.js中定义全局自定义指令

//全局创建自定义指令

Vue.directive('fofo',{

  inserted(el){

// 因为使用的是vant2的Search组件,它里边有很多元素,所以要找到input标签

    let theInput = el.querySelector('input')

    theInput.focus()

  }

})

在页面中使用指令

<van-search placeholder="请输入搜索关键词" background="#007BFF" shape="round" v-fofo/>

在main.js中封装中间件函数插件

实现的效果也是输入框自动聚焦

const directiveObj={

  install(Vue){

    Vue.directive('fofo',{

      inserted(el){

        let theInput = el.querySelector('input')

        theInput.focus()

      }

    })

  }

}

Vue.use(directiveObj)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容