eFolio Week 5 - 0%
本页目录· 18 条
- Grading criteria
- Grade: 1/1
- eFolio Task 5.1
- Screenshot 1: Modified Library form with evidence of password confirmation validation
- Screenshot 2: Using VueJS DevTools to test your components
- eFolio Task 5.2
- router/index.js
- src/App.vue
- src/views/HomeView.vue
- Screenshot of App in Localhost (browser) open on Home page
- Screenshot of App in Localhost (browser) open on About page
- Activity 6: Custom Routing
- 1. Login page
- 2. Authentication
- 3. Authenticated users (Successful login)
- 4. Redirecting Unauthenticated Users
- 5. Conditional Rendering
- 6. Logout Functionality
文件命名: efolio_Week5_FullName_SID.pdfGrading criteria
| 任务 | 未提供(0 分) | 已提供(0.5 分) |
|---|---|---|
| eFolio Week 5 Task 5.1 | 你未提供经过修改且带有密码确认验证证据的 Library 表单截图 | 你已提供经过修改且带有密码确认验证证据的 Library 表单截图 |
| eFolio Week 5 Task 5.2 | 你未完整提供以下文件与截图:• router/index.js• src/App.vue• src/views/HomeView.vue• 浏览器中 localhost 的 Home 页面截图• 浏览器中 localhost 的 About 页面截图 | 你已完整提供以下文件与截图:• router/index.js• src/App.vue• src/views/HomeView.vue• 浏览器中 localhost 的 Home 页面截图• 浏览器中 localhost 的 About 页面截图 |
Grade: 1/1
eFolio Task 5.1
Screenshot 1: Modified Library form with evidence of password confirmation validation
Screenshot 2: Using VueJS DevTools to test your components
eFolio Task 5.2
router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import AboutView from '../views/AboutView.vue'
import LoginView from '../views/LoginView.vue'
const routes = [
{
path: '/',
name: 'Home',
component: HomeView
},
{
path: '/about',
name: 'About',
component: AboutView,
meta: { requiresAuth: true }
},
{
path: '/login',
name: 'Login',
component: LoginView
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
// Global navigation guard - check authentication
router.beforeEach((to, from, next) => {
// Check if route requires authentication
if (to.meta.requiresAuth) {
// Check user login status from localStorage
const isAuthenticated = localStorage.getItem('isAuthenticated') === 'true'
if (isAuthenticated) {
next()
} else {
next('/login')
}
} else {
next()
}
})
export default routersrc/App.vue
<script setup>
import JSONLab from './components/JSONLab.vue'
import BHeader from './components/BHeader.vue'
import LibraryRegistrationForm from './views/HomeView.vue'
</script>
<template>
<header>
<BHeader />
</header>
<main>
<!-- <LibraryRegistrationForm /> -->
<!-- <JSONLab /> -->
<router-view></router-view>
</main>
</template>
<style scoped>
/* header {
line-height: 1.5;
}
.logo {
display: block;
margin: 0 auto 2rem;
}
@media (min-width: 1024px) {
header {
display: flex;
place-items: center;
padding-right: calc(var(--section-gap) / 2);
}
.logo {
margin: 0 2rem 0 0;
}
header .wrapper {
display: flex;
place-items: flex-start;
flex-wrap: wrap;
}
} */
</style>
src/views/HomeView.vue
<script setup>
import { ref } from 'vue'
import DataTable from 'primevue/datatable'
import Column from 'primevue/column'
const formData = ref({
username: '',
password: '',
confirmPassword: '',
isAustralian: false,
reason: '',
gender: '',
suburb: 'Clayton'
})
const submittedCards = ref([])
const submitForm = () => {
validateName(true)
validatePassword(true)
if (!errors.value.username && !errors.value.password) {
submittedCards.value.push({ ...formData.value })
clearForm()
}
}
const clearForm = () => {
formData.value = {
username: '',
password: '',
isAustralian: false,
reason: '',
gender: ''
}
}
const errors = ref({
username: null,
password: null,
confirmPassword: null,
resident: null,
gender: null,
reason: null
})
const validateName = (blur) => {
if (formData.value.username.length < 3) {
if (blur) errors.value.username = 'Name must be at least 3 characters'
} else {
errors.value.username = null
}
}
const validateReason = (blur) => {
if (formData.value.reason.length < 10) {
if (blur) errors.value.reason = 'Reason must be at least 10 characters'
} else {
errors.value.reason = null
}
}
const validatePassword = (blur) => {
const password = formData.value.password
const minLength = 8
const hasUppercase = /[A-Z]/.test(password)
const hasLowercase = /[a-z]/.test(password)
const hasNumber = /\d/.test(password)
const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(password)
if (password.length < minLength) {
if (blur) errors.value.password = `Password must be at least ${minLength} characters long.`
} else if (!hasUppercase) {
if (blur) errors.value.password = 'Password must contain at least one uppercase letter.'
} else if (!hasLowercase) {
if (blur) errors.value.password = 'Password must contain at least one lowercase letter.'
} else if (!hasNumber) {
if (blur) errors.value.password = 'Password must contain at least one number.'
} else if (!hasSpecialChar) {
if (blur) errors.value.password = 'Password must contain at least one special character.'
} else {
errors.value.password = null
}
}
const validateConfirmPassword = (blur) => {
if (formData.value.password !== formData.value.confirmPassword) {
if (blur) errors.value.confirmPassword = 'Passwords do not match.'
} else {
errors.value.confirmPassword = null
}
}
</script>
<template>
<!-- 🗄️ W3. Library Registration Form -->
<div class="container mt-5">
<div class="row">
<div class="col-md-8 offset-md-2">
<h1 class="text-center">🗄️ W4. Library Registration Form</h1>
<p class="text-center">
This form now includes validation. Registered users are displayed in a data table below
(PrimeVue).
</p>
<form @submit.prevent="submitForm">
<div class="row mb-3">
<div class="col-md-6 col-sm-6">
<label for="username" class="form-label">Username</label>
<input
type="text"
class="form-control"
id="username"
@blur="() => validateName(true)"
@input="() => validateName(false)"
v-model="formData.username"
/>
<div v-if="errors.username" class="text-danger">{{ errors.username }}</div>
</div>
<div class="col-md-6 col-sm-6">
<label for="gender" class="form-label">Gender</label>
<select class="form-select" id="gender" v-model="formData.gender" required>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select>
</div>
<div class="col-md-6 col-sm-6">
<label for="password" class="form-label">Password</label>
<input
type="password"
class="form-control"
id="password"
@blur="() => validatePassword(true)"
@input="() => validatePassword(false)"
v-model="formData.password"
/>
<div v-if="errors.password" class="text-danger">{{ errors.password }}</div>
</div>
<div class="col-md-6 col-sm-6">
<label for="confirm-password" class="form-label">Confirm password</label>
<input
type="password"
class="form-control"
id="confirm-password"
v-model="formData.confirmPassword"
@blur="() => validateConfirmPassword(true)"
/>
<div v-if="errors.confirmPassword" class="text-danger">
{{ errors.confirmPassword }}
</div>
</div>
</div>
<div class="row mb-3">
<div class="col-md-6 col-sm-6">
<div class="form-check">
<input
type="checkbox"
class="form-check-input"
id="isAustralian"
v-model="formData.isAustralian"
/>
<label class="form-check-label" for="isAustralian">Australian Resident?</label>
</div>
</div>
</div>
<div class="mb-3">
<label for="reason" class="form-label">Reason for joining</label>
<textarea
class="form-control"
id="reason"
rows="3"
v-model="formData.reason"
@blur="() => validateReason(true)"
@input="() => validateReason(false)"
></textarea>
<div v-if="errors.reason" class="text-danger">{{ errors.reason }}</div>
<div v-if="formData.reason.includes('friend')" class="text-success">
Great to have a friend
</div>
</div>
<div class="mb-3">
<label for="reason" class="form-label">Suburb</label>
<input type="text" class="form-control" id="suburb" v-bind:value="formData.suburb" />
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary me-2">Submit</button>
<button type="button" class="btn btn-secondary" @click="clearForm">Clear</button>
</div>
</form>
</div>
</div>
</div>
<div class="row mt-5">
<h4>This is a Primevue Datatable.</h4>
<DataTable :value="submittedCards" tableStyle="min-width: 50rem">
<Column field="username" header="Username"></Column>
<Column field="password" header="Password"></Column>
<Column field="isAustralian" header="Australian Resident"></Column>
<Column field="gender" header="Gender"></Column>
<Column field="reason" header="Reason"></Column>
</DataTable>
</div>
<div class="row mt-5" v-if="submittedCards.length">
<div class="d-flex flex-wrap justify-content-start">
<div
v-for="(card, index) in submittedCards"
:key="index"
class="card m-2"
style="width: 18rem"
>
<div class="card-header">User Information</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">Username: {{ card.username }}</li>
<li class="list-group-item">Password: {{ card.password }}</li>
<li class="list-group-item">
Australian Resident: {{ card.isAustralian ? 'Yes' : 'No' }}
</li>
<li class="list-group-item">Gender: {{ card.gender }}</li>
<li class="list-group-item">Reason: {{ card.reason }}</li>
</ul>
</div>
</div>
</div>
</template>
<style scoped>
.container {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 80vw;
margin: 0 auto;
padding: 20px;
/* background-color: #e0bfbf; */
border-radius: 10px;
}
/* Class selectors */
.form {
text-align: center;
margin-top: 50px;
}
/* ID selectors */
#username:focus,
#password:focus,
#isAustralian:focus,
.card {
border: 1px solid #ccc;
border-radius: 10px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.card-header {
background-color: #275fda;
color: white;
padding: 10px;
border-radius: 10px 10px 0 0;
}
.list-group-item {
padding: 10px;
}
</style>
Screenshot of App in Localhost (browser) open on Home page
Screenshot of App in Localhost (browser) open on About page
Activity 6: Custom Routing
1. Login page
2. Authentication
<form @submit.prevent="handleLogin" class="mt-4">
<div class="mb-3">
<label for="username" class="form-label">Username</label>
<input
type="text"
class="form-control"
id="username"
v-model="username"
placeholder="Enter your username"
required
/>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input
type="password"
class="form-control"
id="password"
v-model="password"
placeholder="Enter your password"
required
/>
</div>
<div class="d-grid">
<button type="submit" class="btn btn-primary">Login</button>
</div>
<div
v-if="errorMessage"
:class="[
'alert mt-3',
errorMessage.includes('successful') ? 'alert-success' : 'alert-danger'
]"
role="alert"
>
{{ errorMessage }}
</div>
</form>
<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
// Get router instance
const router = useRouter()
// Reactive variables
const username = ref('')
const password = ref('')
const errorMessage = ref('')
// Hardcoded user credentials
const VALID_CREDENTIALS = {
username: 'jimmy',
password: 'areallybadguy'
}
// Login handler function
const handleLogin = () => {
// Clear error message
errorMessage.value = ''
// Basic form validation
if (!username.value || !password.value) {
errorMessage.value = 'Please enter both username and password'
return
}
// Validate user credentials
if (
username.value === VALID_CREDENTIALS.username &&
password.value === VALID_CREDENTIALS.password
) {
// Login successful
console.log('Login successful!')
// Store login status to localStorage
localStorage.setItem('isAuthenticated', 'true')
localStorage.setItem('currentUser', username.value)
// Dispatch custom event to notify other components of status update
window.dispatchEvent(new CustomEvent('auth-status-changed'))
// Show success message
errorMessage.value = 'Login successful! Redirecting...'
// Redirect to home page after delay
setTimeout(() => {
router.push('/')
}, 1500)
} else {
// Login failed
errorMessage.value = 'Invalid username or password. Please try again.'
console.log('Login failed:', { username: username.value, password: password.value })
}
}
</script>3. Authenticated users (Successful login)
user can access About page
4. Redirecting Unauthenticated Users
// Global navigation guard - check authentication
router.beforeEach((to, from, next) => {
// Check if route requires authentication
if (to.meta.requiresAuth) {
// Check user login status from localStorage
const isAuthenticated = localStorage.getItem('isAuthenticated') === 'true'
if (isAuthenticated) {
next()
} else {
next('/login')
}
} else {
next()
}
})5. Conditional Rendering
<!-- Conditional rendering: display different content based on login status -->
<li v-if="!isAuthenticated" class="nav-item">
<router-link to="/login" class="nav-link" active-class="active">Login</router-link>
</li>
<li v-if="isAuthenticated" class="nav-item dropdown">
<a
class="nav-link dropdown-toggle"
href="#"
role="button"
@click="toggleDropdown"
aria-expanded="false"
>
Welcome, {{ currentUser }}
</a>
<ul v-show="showDropdown" class="dropdown-menu show">
<li>
<a class="dropdown-item" href="#" @click="handleLogout">Logout</a>
</li>
</ul>
</li>
6. Logout Functionality
// Logout handler
const handleLogout = () => {
// Clear login status
localStorage.removeItem('isAuthenticated')
localStorage.removeItem('currentUser')
// Update component state
isAuthenticated.value = false
currentUser.value = ''
showDropdown.value = false
// Dispatch custom event to notify other components of status update
window.dispatchEvent(new CustomEvent('auth-status-changed'))
// Redirect to home page
router.push('/')
console.log('User logged out successfully')
}