• Vue2自定义指令改变DOM值后未刷新data中绑定属性的值


    标签(空格分隔): Vue


    自定义指令用于过滤输入框,只允许输入数字:

    Vue.directive('numberOnly', {
        bind: function (el, binding) {
            el.handler = function () {
                el.value = el.value.replace(/[^d]/g, '');
            }
            el.addEventListener('input', el.handler);
        },
        unbind: function (el) {
            el.removeEventListener('input', el.handler);
        }
    });
    

    在DOM中使用如下所示:

    <input type="text" name="image-code" class="input" placeholder="图片验证码" autocomplete="off" v-model="imageCode" v-number-only />
    

    此时可以实现在输入框中只能输入数字,输入其它字符不予显示。但是在提交表单的时候使用this.imageCode却发现,字符中有一个刚才试验的非数字字符,如图所示:

    vue-custom-directive

    这该怎么办呢?通过阅读文档,我目前使用传递自定义指令value属性的方法来data中的属性赋值。使用这个方法,可以不绑定v-mode="",当然绑定了也没什么区别:

    Vue.directive('numberOnly', {
        bind: function (el, binding) {
            el.handler = function () {
                el.value = el.value.replace(/[^d]/g, '');
    
                // 手动刷新data中绑定的属性
                binding.value.set[binding.value.name] = el.value;
            }
            el.addEventListener('input', el.handler);
        },
        unbind: function (el) {
            el.removeEventListener('input', el.handler);
        }
    });
    

    此时在DOM中就需要传递两个属性:

    <input type="text" name="image-code" class="input" placeholder="图片验证码" autocomplete="off" v-model="imageCode" v-number-only="{ set: this, name: 'imageCode' }" />
    

    这样this.imageCode当中就不会出现非数字字符串了。

    你可能想说,直接在set中指定this.imageCode,然后在自定义指令中binding.value.set = el.value;,不就可以了嘛。然而经过测试这样是起不到作用的。

    这个方案并不优雅,如果有其它解决方案,还望不吝赐教。

  • 相关阅读:
    ios10 获取idfa的坑
    iOS 获取手机sim卡的运营商(移动,电信,联通) 相关信息
    iOS获取手机IP地址
    UIScrollView 与 touchesBegan 冲突解决方法
    32位与64位基础
    MySQL数据库基础_表&简单查询
    MySQL数据库基础
    Java_File、递归
    Java_lambda表达式
    Java线程锁,等待唤醒和线程池
  • 原文地址:https://www.cnblogs.com/jehorn/p/7922101.html
Copyright © 2020-2023  润新知