Vueで部分的に入力内容をマスクする
12068 ワード
要件は、入力コンテンツをマスキングする通常の方法242479142を使用して、部分的に隠す入力コンテンツを隠すことです.しかし、それは、部分的にマスクされたコンテンツを表示する要件を満たしていない+元のマスクされていないコンテンツを失うことなく、unmaskedコンテンツを休ませる.
オンラインリソースを検索して、記事は前にこの問題に対処していない.ほとんどの記事は完全にマスクされた入力コンテンツを行う方法についてのチュートリアルですが、部分的にマスクされません.私は自分自身の実施をすることにした.
VUEの上にこのコンポーネントをビルドすると、この方法が行われます.ユーザカーソル位置は最初の問題です、ユーザー操作に基づいて削除か挿入値のために現在のカーソル位置を見つける必要があります.カーソル電流がどこで止まるかを見つける方法.で、ブラウザは実際にこれを達成するAPIを提供しています.入力にユーザーの動作を追跡するために、以前の値と現在の値は、それが削除か挿入かどうか決定するために比較しました.
次のステップは、入力に新しい値をレンダリングするために所定のマスキングルールを使用して新しい値をレンダリングするには、最後の2文字が残りの文字列で文字列が表示される必要があると言うことができます
全体のビューのために.
オンラインリソースを検索して、記事は前にこの問題に対処していない.ほとんどの記事は完全にマスクされた入力コンテンツを行う方法についてのチュートリアルですが、部分的にマスクされません.私は自分自身の実施をすることにした.
VUEの上にこのコンポーネントをビルドすると、この方法が行われます.ユーザカーソル位置は最初の問題です、ユーザー操作に基づいて削除か挿入値のために現在のカーソル位置を見つける必要があります.カーソル電流がどこで止まるかを見つける方法.で、ブラウザは実際にこれを達成するAPIを提供しています.入力にユーザーの動作を追跡するために、以前の値と現在の値は、それが削除か挿入かどうか決定するために比較しました.
const preInput = this.preInput;
const index = e.target.selectionStart;
const nowValue = e.target.value;
//compare length of previous current input value
const increment = nowValue.length - preInput.length;
NowValueが長い場合、新しい値はif (increment >= 0) {
const newStr = nowValue.slice(index - increment, index);
this.preInput = preInput.slice(0, index - increment) + newStr
preVal.slice(index - increment)
}
一方、何らかの入力が削除された場合else if (increment < 0) {
this.preInput = preInput.slice(0, index) +
preInput.slice(index - increment);
}
削除または挿入を知っていて、更新された値を得てください.次のステップは、入力に新しい値をレンダリングするために所定のマスキングルールを使用して新しい値をレンダリングするには、最後の2文字が残りの文字列で文字列が表示される必要があると言うことができます
if (nowValue.length > 0) {
const len = nowValue.length-2 > 0 ? nowVal.length - 2 : 0;
e.target.value = new Array(len).fill('*').join("") +
nowValue.slice(len);
}
ここで、マスクされた値は、マスクされたシンボルを持つコンテンツの配列塗りつぶしの方法で作成され、ネイティブプロパティを入力して更新されます.元の値はpreinputに格納されます.この円の最後にconsole.log("original content:", this.preInput)
未マスクのオリジナルコンテンツを取得します.全体のビューのために.
//v-model needs to be indicate in order for input to receive value
<input v-model="hiddenInput" @input="onInput"/>
onInput(e){
const preInput = this.preInput;
const index = e.target.selectionStart;
const nowValue = e.target.value;
const increment = nowValue.length - preInput.length;
if (increment >= 0) {
const newStr = nowValue.slice(index - increment, index);
this.preInput = preInput.slice(0, index - increment) +
newStr + preVal.slice(index - increment)
} else if (increment < 0) {
this.preInput = preInput.slice(0, index) +
preInput.slice(index - increment);
}
if (nowValue.length > 0) {
//define the mask rule, here is to visualize last two digits
const len = nowValue.length-2 > 0 ? nowVal.length - 2 : 0;
e.target.value = new Array(len).fill('*').join("") +
nowValue.slice(len);
}
//update cursor
e.target.setSelectionRange(index, index)
}
インスピレーションのためにReference
この問題について(Vueで部分的に入力内容をマスクする), 我々は、より多くの情報をここで見つけました https://dev.to/yorrran/partially-mask-your-input-content-with-vue-6ffテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol