添加全局自动聚焦的Vue自定义功能

import Vue from "vue"

// 标签添加自动聚焦的功能
// 用法:

Vue.directive("fofo",{

 inserted(el){

  fo(el)

},

  update (el) { //指令所在的标签被更新时候,触发

  fo(el)
})


function fo (el) {

// el是所在的标签

if(el.nodeName === "INPUT" || el.nodeName === "TEXTAREA") {

// el本身的标签名就是input或者是textarea

el.focus()

}else {

// 如果不是就往下在找找调用focus()

const input = el.querySelector("input")

const textarea = el.querySelector("textarea")

 if (input || textarea) {

        input && input.focus()

        textarea && textarea.focus()
}else {

console.log("请把v-fofo放在输入框标签上")

}

1.自定义节点在src/utils/directives.js中书写以上代码

2.在main.js中import "@/utils/directives.js"

3.在你想自动聚焦的input或者textarea上就可以使用 v-fofo 来自动聚焦啦

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
抱歉,作为语言AI模型,我没有具体的实现能力,无法为您提供需要的答案。但是,我可以为您提供一些有关Vue自定义指令的基本知识。 Vue自定义指令可以全局注册或者局部注册。全局注册指令可以在任何Vue实例中使用,而局部注册指令只能在特定的Vue实例中使用。 全局注册自定义指令的方法是: ``` Vue.directive('directiveName', { //指令的定义 }) ``` 其中,'directiveName' 是指令的名称,{}内是指令的定义。 局部注册自定义指令的方法是: ``` new Vue({ directives: { directiveName: { // 指令的定义 } } }) ``` 在实现一个网站的登陆页面时,我们可以用自定义全局指令和局部指令来实现一些交互效果,例如: 全局指令: 1. 自动聚焦:当页面加载完成后,输入框自动聚焦。 ``` Vue.directive('focus', { inserted: function (el) { el.focus() } }) ``` 在输入框中加入 v-focus 即可实现自动聚焦效果。 2. 防抖动:在输入框中输入时,延迟一定时间后再发生请求,防止因为输入过于频繁而发生多次请求。 ``` Vue.directive('debounce', { inserted: function (el, binding) { let timer el.addEventListener('input', () => { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { binding.value() }, 500) }) } }) ``` 在输入框中加入 v-debounce="sendRequest",sendRequest为方法的名称即可实现防抖动效果。 局部指令: 1. 自动聚焦:同全局指令中的自动聚焦。 ``` directives: { focus: { inserted: function (el) { el.focus() } } } ``` 加入 v-focus 即可实现自动聚焦效果。 2. 双向绑定密码框的内容:使输入的密码随着输入动态显示到页面上。 ``` directives: { password: { twoWay: true, priority: 1000, bind: function () { this.handler = () => { this.set(this.el.value) } this.el.addEventListener('input', this.handler) }, update: function (newValue) { this.el.value = newValue }, unbind: function () { this.el.removeEventListener('input', this.handler) } } } ``` 在密码框中加入 v-model="password | password" 即可实现双向绑定效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值