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;,不就可以了嘛。然而經過測試這樣是起不到作用的。

這個方案並不優雅,如果有其它解決方案,還望不吝賜教。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM