本文将介紹以下内容:
- 概述
- 建立一個項目
- 安裝 element-plus
- 安裝 vue-router
- 編寫登入頁面以及邏輯
概述
要使用Vue 3、Vite、Element Plus 、Vue Router 建立一個登入頁.
建立一個項目
使用 NPM 指令建立一個vite項目
npm init vite@latest
輸入項目名稱 vite-login,選擇 Vue,選擇 TypeScript
√ Select a framework: » Vue
√ Select a variant: » TypeScript
加載依賴項:npm install
PS ***\vite-login> npm install
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE package: '[email protected]',
npm WARN EBADENGINE required: { node: '>=14.18.0', npm: '>=8.0.0' },
npm WARN EBADENGINE current: { node: 'v16.5.0', npm: '7.19.1' }
npm WARN EBADENGINE }
added 42 packages, and audited 43 packages in 11s
3 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
安裝 element-plus
進入項目目錄,并在終端中運作以下指令,安裝指令:npm install element-plus。
PS ***\vite-login> npm install element-plus
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE package: '[email protected]',
npm WARN EBADENGINE required: { node: '>=14.18.0', npm: '>=8.0.0' },
npm WARN EBADENGINE current: { node: 'v16.5.0', npm: '7.19.1' }
npm WARN EBADENGINE }
added 22 packages, and audited 65 packages in 12s
8 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
安裝 vue-router
進入項目目錄,并在終端中運作以下指令,安裝指令:npm install vue-router。
PS ***\vite-login> npm install vue-router
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE package: '[email protected]',
npm WARN EBADENGINE required: { node: '>=14.18.0', npm: '>=8.0.0' },
npm WARN EBADENGINE current: { node: 'v16.5.0', npm: '7.19.1' }
npm WARN EBADENGINE }
added 2 packages, and audited 67 packages in 2s
9 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
編寫頁面
建立頁面
在項目根目錄中的src下建立一個檔案夾建立views檔案夾,建立 home.vue 、login.vue 空内容,待用。
<!-- login.vue -->
<template>
<h1>Login Page</h1>
</template>
<script lang="ts" setup>
</script>
<template>
<h1>Home Page</h1>
</template>
<script lang="ts" setup>
</script>
配置 router
在項目根目錄下建立一個新的檔案夾,命名為router,并在該檔案夾下建立一個新的檔案,命名為index.js。
// /rotuer/index.ts
import { createRouter, createWebHistory } from "vue-router";
import HomePage from '@/views/Home.vue';
import LoginPage from '@/views/Login.vue';
const routes = [
{
path:'/',
name:'Default',
component:HomePage
},
{
path:'/home',
name:'Home',
component:HomePage
},
{
path:'/login',
name:'Login',
component:LoginPage
}
];
const router = createRouter({
history: createWebHistory(),
routes: routes,
});
export default router;
在主應用程式檔案中引入 router。打開src/main.js檔案,并添加以下代碼。
// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import router from '../router';
createApp(App).use(router).mount('#app')
運作項目npm run dev
解決 @ 的異常路徑問題
打開浏覽器異常:[plugin:vite:import-analysis] Failed to resolve import "@/views/Home.vue" from "router\index.ts". Does the file exist?
第一種方式:直接修改 /router/index.ts 的import 的路徑
// 修改前
import HomePage from '@/views/Home.vue';
import LoginPage from '@/views/Login.vue'
// 修改後
import HomePage from '../src/views/Home.vue';
import LoginPage from '../src/views/Login.vue';
直接重新整理頁面:
第二種:檢查配置
- 檢查tsconfig.json配置:如果你正在使用TypeScript,打開項目根目錄下的tsconfig.json檔案,确認是否有以下配置項:
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
如果沒有這個配置項,添加它并重新啟動項目。
- 檢查vite.config.js配置:在項目根目錄下,找到vite.config.js檔案,檢查是否有以下配置項:
import { defineConfig } from 'vite'
// https://vitejs.dev/config/
export default defineConfig({
resolve:{
alias:{
'@':'/src'
}
}
})
如果沒有這個配置項,添加它并重新啟動項目。
配置 element-plus
在主應用程式檔案中引入Element Plus:打開src/main.js檔案,并添加以下代碼。
import { createApp } from 'vue'
import App from './App.vue'
import router from '../router';
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
createApp(App).use(router).use(ElementPlus).mount('#app')
修改登入頁
在該檔案中編寫登入頁的HTML和邏輯代碼。以下是一個簡單的示例:
<!-- @/views/Login.vue -->
<template>
<div class="login-container">
<el-form ref="formRef" :model="formData" :rules="formRules" class="login-form">
<h2 class="login-title">登入</h2>
<el-form-item prop="username">
<el-input v-model="formData.username" placeholder="請輸入使用者名"></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input v-model="formData.password" type="password" placeholder="請輸入密碼"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm">登入</el-button>
<el-button type="primary" @click="resetForm">重置</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
const formData = ref({
username: '',
password: '',
});
const formRules = ref({
username: [
{ required: true, message: '請輸入使用者名', trigger: 'blur' },
],
password: [
{ required: true, message: '請輸入密碼', trigger: 'blur' },
],
});
const formRef = ref();
const resetForm = () => {
if (!formRef) return
formRef.value.resetFields()
}
const submitForm = () => {
console.log("formRef.value:", formRef.value);
formRef.value.validate((valid: any) => {
if (valid) {
// 表單校驗通過,可以進行送出操作
console.log('表單校驗通過');
console.log(formData.value); // 擷取表單資料
} else {
// 表單校驗失敗,可以進行錯誤處理
console.log('表單校驗失敗');
return false;
}
});
};
</script>
<style scoped>
.login-container {
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.login-form {
max-width: 400px;
width: 100%;
}
.login-title {
text-align: center;
font-size: 24px;
margin-bottom: 20px;
}
</style>
添加登入邏輯
進入首頁的時候判斷是否登入,未登入則進入登入頁。
<!--App.vue-->
<template>
<h1 v-if="isLogged">歡迎通路首頁</h1>
<router-view></router-view>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
const isLogged = ref(false);
const router = useRouter();
const checkLoginStatus = () => {
let isLoggedIn = false;
isLogged.value = isLoggedIn;
};
onMounted(() => {
setTimeout(() => {
checkLoginStatus();
if (!isLogged.value) {
router.push('/login');
return;
}
router.push('/');
});
});
</script>
<style scoped></style>
預設進入首頁判斷是否登入,未登入直接跳轉 /login,已登入進入首頁
const checkLoginStatus = () => {
let isLoggedIn = false; // 預設 未登入,進入登入頁
isLogged.value = isLoggedIn;
};
onMounted(() => {
setTimeout(() => {
checkLoginStatus();
if (!isLogged.value) {
router.push('/login');
return;
}
router.push('/');
});
});
const checkLoginStatus = () => {
let isLoggedIn = tre; // 預設 已登入,進入首頁
isLogged.value = isLoggedIn;
};
onMounted(() => {
setTimeout(() => {
checkLoginStatus();
if (!isLogged.value) {
router.push('/login');
return;
}
router.push('/');