美文网首页
vue中,阻止默认事件

vue中,阻止默认事件

作者: 清风徐来_简 | 来源:发表于2020-01-10 13:44 被阅读0次

在vue项目中,遇到这样一个需求:页面中有好多输入框,在某一个输入框中按Tab键时不触发默认事件,而是变成输入两个空格。

  • 这里面有一些注意点

    1,vue项目
    2,众多输入框中的某一个输入框
    3,按下Tab键,事件监听
    4,阻止默认事件,变成自定义事件

  • 这就有了一个思路:

    当焦点在本输入框时,添加事件监听(阻止默认事件,变成自定义的)。
    当失去焦点时,移除事件监听(只在本输入框内生效,其他输入框不生效)。

  • 用vue的写法就是:
    <el-input v-model="ruleForm.extras" type="textarea" style="padding-right:15em;"
                  id="freeinput"
                  :rows="6"
                  placeholder="请输入自由条件内容(json格式)"
                  @focus="add_eventListener"
                  @blur="remove_eventListener">
    </el-input>
    
    methods:{                         
            //在vue项目中,需要将事件监听封装成函数,让this托管,才能生效,所以是这样的写法。 
            add_eventListener() {
                window.addEventListener('keydown', this.keyFun, true)
            },        
            remove_eventListener() {
                window.removeEventListener('keydown', this.keyFun, true)
            },    
            keyFun(event) {
                if (event.keyCode === 9) {
                    // 阻止默认事件
                    event.preventDefault(); 
                    let ids = "  ";
                    // 获取对应标签
                    let obj = document.getElementById('freeinput');
                    // 获取光标的起始位置, 在未做人为选中的情况下, start和end是一样的
                    let start = obj.selectionStart; // 注意:使用vue对象时,没有selectionStart/selectionEnd属性,所以换成了原生js对象
                    let end = obj.selectionEnd;
                    // 获取选中的文本
                    let text = window.getSelection().toString();
                    // 如果有换行符, 需要替换, 实现效果同代码编辑器的选中集体缩进
                    text = ids + text.replace(/\n/g, '\n' + ids);
                    // 在原始光标位置中插入tab对应的字符
                    obj.value = obj.value.substring(0, start) + text + obj.value.substring(end); 
                    // 将光标设置到新的位置
                    obj.setSelectionRange(start + ids.length, start + text.length);
                }
            }
        }
    
  • 效果图:
    处理前按Tab键效果.gif 处理后按Tab键效果.gif

相关文章

  • Vue知识点笔记2

    Vue指令之事件修饰符:.stop 阻止冒泡(写在子元素中阻止其触发父元素事件).prevent 阻止默认事件.c...

  • vue中,阻止默认事件

    在vue项目中,遇到这样一个需求:页面中有好多输入框,在某一个输入框中按Tab键时不触发默认事件,而是变成输入两个...

  • vue30道面试题

    vue的修饰符 1.事件修饰符 prevent 阻止默认事件(在指定的事件后进行默认事件的阻止) stop阻止事件...

  • vue事件、指令、钩子

    vue事件、指令、钩子 vue的事件修饰符:.stop:阻止冒泡.prevent:阻止默认行为.capture:捕...

  • vue

    vue的事件修饰符:.stop:阻止冒泡.prevent:阻止默认行为.capture 捕获.self ...

  • vue

    vue的事件修饰符: .stop:阻止冒泡 .prevent:阻止默认行为 .capture .self .onc...

  • vue学习(10)事件修饰符

    知识点: vue事件修饰符:1.prevent:阻止默认事件。(常用)2.stop:阻止冒泡事件。(常用)3.on...

  • vue

    vue的事件修饰符:.stop:阻止冒泡.prevent:阻止默认行为.capture.self CommonJS...

  • vue

    vue的事件修饰符:.stop:阻止冒泡.prevent:阻止默认行为.capture.self CommonJS...

  • vue

    vue的事件修饰符:.stop:阻止冒泡.prevent:阻止默认行为.capture.self CommonJS...

网友评论

      本文标题:vue中,阻止默认事件

      本文链接:https://www.haomeiwen.com/subject/xrmpactx.html