はじめに
このプロジェクトでは、携帯電話番号の認証コードを使ってアカウント認証機能を実装する方法を学びます。この機能は、現在多くのプラットフォームで一般的に使われており、ユーザーがログインする際の追加のセキュリティと利便性を提供します。
👀 プレビュー


🎯 タスク
このプロジェクトでは、以下を学びます。
- 認証コードを送信する機能を実装する方法
- 入力された認証コードを検証する機能を実装する方法
- Element Plus における
Notificationコンポーネントの使い方を理解する方法
🏆 成果
このプロジェクトを完了すると、以下のことができるようになります。
- ユーザー入力と検証を処理する
- 動的な認証コードを生成して管理する
Notificationコンポーネントを使って成功とエラーメッセージを表示する- Vue.js と Pinia を使ってコンポーネントの切り替えと状態管理を実装する
プロジェクト構造を設定する
このステップでは、プロジェクト構造を設定する方法を学びます。以下の手順に従ってこのステップを完了しましょう。
このプロジェクトのプロジェクトフォルダを開きます。ディレクトリ構造は以下の通りです。
├── css
│ ├── element-plus@2.3.7
│ │ ├── index.css
│ │ └── index.full.js
│ └── index.css
├── images
│ └── arrow.png
├── index.html
└── js
├── index.mjs
├── pinia.esm-browser.js
├── vue3.global.js
└── vue.esm-browser.prod.js
その中で:
cssは、ページの参照スタイルを格納するフォルダです。imagesは、ページの参照画像を格納するフォルダです。jsは、ページの参照 JavaScript ファイルを格納するフォルダです。index.htmlは、完成させる必要のあるファイルです。
WebIDE の右下隅にあるGo Liveボタンをクリックして、プロジェクトを実行します。
次に、VM の上部にある「Web 8080」を開き、手動で更新するとページが表示されます。
変数と関数を提供する
このステップでは、後続のステップで必要な変数と関数を取得します。
- 提供されたプロジェクト内の
index.htmlファイルを開きます。 const { createApp, reactive, toRefs } = Vue;を探して、後続の使用のために以下のコードのように追加します。
const { createApp, reactive, toRefs, provide, inject, ref, watch } = Vue;
const { createApp, reactive, toRefs, provide, inject, ref, watch } = Vue; 3. 最初の// TODOを探して、以下のコードを追加します。
const app = createApp({
setup() {
let data = reactive({
showName: "phone"
});
// TODO
const code = ref([]);
const phoneVal = ref("");
const createCode = function () {
let res = "";
function* _create() {
let count = 0;
while (++count <= 6) {
yield Math.floor(Math.random() * 10);
}
}
for (const iterator of _create()) {
res += iterator;
}
return res;
};
const handlePhone = (num) => {
let res = "";
for (let idx in num) {
if (idx > 2 && idx < num.length - 2) {
res += "*";
} else {
res += num[idx];
}
}
return res;
};
provide("code", code);
provide("phoneVal", phoneVal);
provide("createCode", createCode);
provide("data", data);
provide("handlePhone", handlePhone);
return {
...toRefs(data)
};
}
});
上記のコードでは、createCode()関数は 6 桁のキャプチャコードを作成し、handlePhone()関数は電話番号を単純に暗号化します。
認証コードを送信する機能を実装する
このステップでは、認証コードを送信する機能を実装する方法を学びます。以下の手順に従ってこのステップを完了しましょう。
- 提供されたプロジェクト内の
index.htmlファイルを開きます。 <template id="phone">セクションにバインドイベントを追加します。
<!-- phone -->
<template id="phone">
<div>
<ul class="phone">
<span>Enter cell phone number</span>
<li>
<input type="text" v-model="phoneVal" autofocus id="numberInput" />
</li>
<li>
<input type="checkbox" v-model="isSure" name="" id="checkbox" />
<span
>Have read and agree to the
<a href="javascript:;">Service Agreement</a>
and
<a href="javascript:;">Privacy Guidelines</a>
</span>
</li>
<button id="btn" @click="nextStep">Next</button>
</ul>
</div>
</template>
<!-- phone -->
phoneコンポーネントのsetup()関数で、必要な変数と関数をインジェクトします。
app.component("phone", {
template: "#phone",
setup() {
// TODO
let isSure = ref("");
let phoneVal = inject("phoneVal");
let code = inject("code");
let createCode = inject("createCode");
let data = inject("data");
return {};
}
});
- 電話番号の妥当性をチェックする
verifyPhone()関数を実装します。
function verifyPhone(num) {
if (num.length != 11) return false;
return num[0] == 1 && num[1] == 8;
}
nextボタンのクリックを処理するnextStep()関数を実装します。phoneコンポーネントのすべてのコードは以下の通りです。
app.component("phone", {
template: "#phone",
setup() {
// TODO
let isSure = ref("");
let phoneVal = inject("phoneVal");
let code = inject("code");
let createCode = inject("createCode");
let data = inject("data");
function verifyPhone(num) {
if (num.length != 11) return false;
return num[0] == 1 && num[1] == 8;
}
return {
isSure,
phoneVal,
nextStep() {
if (!isSure.value)
return ElNotification({
title: "Sent Failed",
message: "Please read and agree to the agreement below",
type: "error"
});
if (!verifyPhone(phoneVal.value))
return ElNotification({
title: "Sent Failed",
message: "Invalid phone number",
type: "error"
});
code.value = createCode();
ElNotification({
title: "Sent Successfully",
message: "Your verification code is " + code.value,
type: "success"
});
data.showName = "check";
}
};
}
});
この関数では、まずユーザーが条件に同意しているかどうかを確認します。同意していない場合は、エラー通知を表示します。次に、verifyPhone()関数を使って電話番号の妥当性を確認します。電話番号が無効な場合は、エラー通知を表示します。両方の条件が満たされている場合は、createCode()関数を使ってランダムな 6 桁の認証コードを生成し、成功通知を表示し、コンポーネントをcheckコンポーネントに切り替えます。
入力された認証コードを検証する機能を実装する
このステップでは、入力された認証コードを検証する機能を実装する方法を学びます。以下の手順に従ってこのステップを完了しましょう。
- 提供されたプロジェクト内の
index.htmlファイルを開きます。 <template id="check">セクションにバインドイベントを追加します。
<!-- check -->
<template id="check">
<ul class="number">
<span>Enter SMS verification code</span>
<li class="hassend">
A verification code has been sent to
<i>{{handlePhoneVal}}</i>
</li>
<li class="code-container">
<input type="number" class="code" min="0" max="9" required />
<input type="number" class="code" min="0" max="9" required />
<input type="number" class="code" min="0" max="9" required />
<input type="number" class="code" min="0" max="9" required />
<input type="number" class="code" min="0" max="9" required />
<input type="number" class="code" min="0" max="9" required />
</li>
<a href="javascript:;" id="resend" @click="resentCode">Resend</a>
</ul>
</template>
<!-- check -->
checkコンポーネントに必要な変数と関数を追加します。
app.component("check", {
template: "#check",
setup() {
// TODO
let phoneVal = inject("phoneVal"),
handlePhoneVal = inject("handlePhone")(phoneVal.value),
data = inject("data"),
code = inject("code"),
createCode = inject("createCode"),
rVal = "";
return {};
}
});
- 認証コードの入力を処理するロジックを実装します。
setTimeout(() => {
let oCodeIptList = [...document.getElementsByClassName("code")];
oCodeIptList[0].focus();
oCodeIptList.map((item) => {
item.oninput = function () {
if (item.value) {
item?.nextElementSibling && item?.nextElementSibling.focus();
} else {
item?.previousElementSibling && item?.previousElementSibling.focus();
}
rVal = (oCodeIptList.map((item) => item.value) + "").replaceAll(",", "");
trackVal(rVal);
};
});
function trackVal(val) {
if (val.length >= 6) {
if (val == code.value) {
ElNotification({
title: "Verification Successful",
message: "Welcome back",
type: "success"
});
data.showName = "success";
} else {
ElNotification({
title: "Verification Failed",
message: "The verification code you entered is incorrect",
type: "error"
});
[...document.getElementsByClassName("code")].map(
(item) => (item.value = "")
);
[...document.getElementsByClassName("code")][0].focus();
}
}
}
});
このコードでは、まず認証コードの最初の入力フィールドにフォーカスを当てます。次に、各入力フィールドにoninputイベントハンドラを追加します。ユーザーが値を入力すると、カーソルが自動的に次の入力フィールドにジャンプします。ユーザーが値を削除すると、カーソルが自動的に前の入力フィールドにジャンプします。
また、入力された認証コードを検証するtrackVal()関数も実装しています。入力が 6 桁で生成された認証コードと一致する場合、成功通知を表示してコンポーネントをsuccessコンポーネントに切り替えます。入力が間違っている場合、入力フィールドをクリアしてエラー通知を表示します。
- 認証コードを再送信する
resentCode()関数を実装します。checkコンポーネントのすべてのコードは以下の通りです。
app.component("check", {
template: "#check",
setup() {
// TODO
let phoneVal = inject("phoneVal"),
handlePhoneVal = inject("handlePhone")(phoneVal.value),
data = inject("data"),
code = inject("code"),
createCode = inject("createCode"),
rVal = "";
setTimeout(() => {
let oCodeIptList = [...document.getElementsByClassName("code")];
oCodeIptList[0].focus();
oCodeIptList.map((item) => {
item.oninput = function () {
if (item.value) {
item?.nextElementSibling && item?.nextElementSibling.focus();
} else {
item?.previousElementSibling &&
item?.previousElementSibling.focus();
}
rVal = (oCodeIptList.map((item) => item.value) + "").replaceAll(
",",
""
);
trackVal(rVal);
};
});
function trackVal(val) {
if (val.length >= 6) {
if (val == code.value) {
ElNotification({
title: "Verification Successful",
message: "Welcome back",
type: "success"
});
data.showName = "success";
} else {
ElNotification({
title: "Verification Failed",
message: "The verification code you entered is incorrect",
type: "error"
});
[...document.getElementsByClassName("code")].map(
(item) => (item.value = "")
);
[...document.getElementsByClassName("code")][0].focus();
}
}
}
});
return {
handlePhoneVal,
resentCode() {
code.value = createCode();
ElNotification({
title: "Sent Successfully",
message: "Your verification code is " + code.value,
type: "success"
});
}
};
}
});
この関数は新しい認証コードを生成し、成功通知を表示します。
以上です!これで携帯電話番号の認証コードを使ったアカウント認証機能の実装が完了しました。
最終的な結果は以下の通りです。


まとめ
おめでとうございます!このプロジェクトを完了しました。実力を向上させるために、LabEx でさらに多くの実験を行って練習してください。



