zoukankan      html  css  js  c++  java
  • vue自定义指令input获取焦点,及不生效解决办法 Jim

    全局注册

    方式一:

    1.新建一个js文件,里面写自定义指令的方法类
    2.引入到main.js中,里面注册全局指令
    // 第一步
    const focusDirective = {
        inserted(el) {
            el.focus();
        },
    }
    
    export default focusDirective
    // 第二步 main.js中注册指令
    import Vue from 'vue';
    import focusDirective from './focusDirective';
    
    Vue.directive('focus', focusDirective);

    使用 :

    <a-input v-focus></a-input>

    方式二:

    1.新建一个js文件,里面写自定义指令的方法类,并注册
    2.引入到main.js中
    // 第一步
    import Vue from 'vue';
    const focusDirective = {
        inserted(el) {
            el.focus();
        },
    }
    Vue.directive('focus', focusDirective)
    
    // 第二步 main.js中注册指令
    import './focusDirective';

    局部注册(指的是单个vue组件内注册)

    <template>
        <input type="number v-focus></input>
    </template>
    
    <script>
    export default {
        data() {},
        directives: {
            focus: {
                inserted(el) {
                    el.focus();
                }
            }
        }
    }
    </script>
    • directive参数
    • 1、钩子
      // 只调用一次 指令第一次绑定到元素时触发
      bind(el, binding, vnode, oldvnode) {}
      // 被绑定元素插入到父节点时调用
      inserted(el, binding, vnode, oldvnode) {}
      // 组件所在的VNode更新时触发,
      update(el, binding, vnode, oldvnode) {}
      // 指令所在组件的VNode及其子VNode 更新之后触发
      componentUpdated(el, binding, vnode, oldvnode) {}
      // 只调用一次 指定与元素解绑时触发
      unbind(el, bingding, vnode, oldvnode) {}

      2、参数
      el 指的是所绑定的Dom元素
      el.dataset 指的是元素自定义的参数值,可以修改,可以用来和上面的钩子函数之前传递信息

      
      

      bingding 是一个对象
      name: 去掉"v-"及后缀后的名称
      rawName: 自定义的全部名称
      express: 是个字符串,展示指令绑定的值value
      value: 指令绑定的值
      arg: 传给指令的参数,如果没有传给指令参数则不会出现此参数

       

       自动获取焦点不生效分析

    • 经过打断点发现,a-input中通过v-focus进来的el参数并非是input元素,而是父级div元素,代码改成下面就好了
      const focusDirective = {
          inserted (el) {
              if (el.tagName.toLocaleLowerCase() == 'input') {
                  el.focus()
              } else {
                  if (el.getElementsByTagName('input')) {
                      el.getElementsByTagName('input')[0].focus()
                  }
              }
          }
      
      }
      export default focusDirective
  • 相关阅读:
    Nginx 高级配置
    nginx安装和优化配置
    location语法介绍
    iptables
    通过 loganalyzer 展示数据库中的系统日志
    ubuntu_server16.04详细安装步骤
    内存控制mmap的原型和使用方法
    C语言中open函数read函数lseek函数是如何使用的
    gdb调试工具的基本使用
    C语言如何制作静态库
  • 原文地址:https://www.cnblogs.com/huoshengmiao/p/15773677.html
Copyright © 2011-2022 走看看