重构已有前端代码

newzwz
lee-zt 2 months ago
parent 9f79bd04e1
commit 1ae1607686

@ -7,17 +7,9 @@
</template> </template>
<!-- 控制模板数据与行为 --> <!-- 控制模板数据与行为 -->
<script> <script setup lang="js" name="App">
//import MainPage from './components/MainPage.vue';
import Header from './components/Header.vue'; import Header from './components/Header.vue';
import {RouterView} from 'vue-router'; import { RouterView } from 'vue-router';
export default {
name: 'App',
components: {
Header,
RouterView
}
}
</script> </script>
<!-- 样式部分,定义CSS样式 --> <!-- 样式部分,定义CSS样式 -->

@ -71,7 +71,7 @@
</div> </div>
</template> </template>
<script setup name="UserLogin"> <script lang="js" setup name="UserLogin">
import { ref, computed } from 'vue'; import { ref, computed } from 'vue';
import request from '@/utils/request'; import request from '@/utils/request';
import { ElMessage } from 'element-plus'; import { ElMessage } from 'element-plus';

@ -15,34 +15,25 @@
</div> </div>
</template> </template>
<script> <script setup lang="js" name="LoginRegisterModal">
import { ref } from 'vue'; import { ref } from 'vue';
// //
import UserLogin from './Login.vue'; import UserLogin from './Login.vue';
import UserRegister from './Register.vue'; import UserRegister from './Register.vue';
export default { const emit = defineEmits(['close']);
name: 'LoginRegisterModal',
components: {
UserLogin, //
UserRegister //
},
setup(props, { emit }) {
//
const isLogin = ref(true);
// / const isLogin = ref(true);
const toggleForm = () => {
isLogin.value = !isLogin.value;
};
return { // /
isLogin, const toggleForm = () => {
toggleForm, isLogin.value = !isLogin.value;
close: () => {emit('close')} // };
};
} //
} const close = () => {
emit('close');
};
</script> </script>
<style scoped> <style scoped>

@ -27,60 +27,45 @@
</div> </div>
</template> </template>
<script> <script setup lang="js" name="NoticeBoard">
import { ref, onMounted, onUnmounted } from 'vue'; import { ref, onMounted, onUnmounted } from 'vue';
export default { const images = ref([
name: 'NoticeBoard', { src: require('@/assets/whu1.jpg'), alt: '公告图片1' },
setup() { { src: require('@/assets/whu2.jpg'), alt: '公告图片2' },
const images = ref([ { src: require('@/assets/whu3.jpg'), alt: '公告图片3' },
{ src: require('@/assets/whu1.jpg'), alt: '公告图片1' }, { src: require('@/assets/whu4.jpg'), alt: '公告图片4' },
{ src: require('@/assets/whu2.jpg'), alt: '公告图片2' }, { src: require('@/assets/whu5.jpg'), alt: '公告图片5' },
{ src: require('@/assets/whu3.jpg'), alt: '公告图片3' }, ]);
{ src: require('@/assets/whu4.jpg'), alt: '公告图片4' },
{ src: require('@/assets/whu5.jpg'), alt: '公告图片5' }, const currentIndex = ref(0);
]);
//
const currentIndex = ref(0); const nextImage = () => {
currentIndex.value = (currentIndex.value + 1) % images.value.length;
//
const nextImage = () => {
currentIndex.value = (currentIndex.value + 1) % images.value.length;
};
//
const prevImage = () => {
currentIndex.value =
(currentIndex.value - 1 + images.value.length) % images.value.length;
};
//
const goToImage = (index) => {
currentIndex.value = index;
};
//
let interval = null;
onMounted(() => {
//
interval = setInterval(nextImage, 5000);
});
onUnmounted(() => {
//
clearInterval(interval);
});
return {
images,
currentIndex,
nextImage,
prevImage,
goToImage,
};
},
}; };
//
const prevImage = () => {
currentIndex.value =
(currentIndex.value - 1 + images.value.length) % images.value.length;
};
//
const goToImage = (index) => {
currentIndex.value = index;
};
//
let interval = null;
onMounted(() => {
interval = setInterval(nextImage, 5000);
});
onUnmounted(() => {
clearInterval(interval);
});
</script> </script>
<style scoped> <style scoped>

@ -36,79 +36,69 @@
</div> </div>
</template> </template>
<script> <script setup lang="js" name="PostPage">
import { ref } from 'vue'; import { ref } from 'vue';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
export default {
name: 'PostPage', const categories = ref(['全部', '学习', '娱乐', '二手交易']);
setup() { const selectedCategory = ref('全部');
const categories = ref(['全部', '学习', '娱乐', '二手交易']); const posts = ref([
const selectedCategory = ref('全部'); {
const posts = ref([ id: 1,
{ category: '学习',
id: 1, title: '如何高效学习?',
category: '学习', summary: '分享一些学习技巧...',
title: '如何高效学习?', avatar: require('@/assets/default-avatar/boy_1.png'),
summary: '分享一些学习技巧...', likes: 1200,
avatar: require('@/assets/default-avatar/boy_1.png'), comments: 10,
likes: 1200, favorites: 100,
comments: 10, },
favorites: 100, {
}, id: 2,
{ category: '娱乐',
id: 2, title: '最近的热门电影推荐',
category: '娱乐', summary: '看看这些电影吧...',
title: '最近的热门电影推荐', avatar: require('@/assets/default-avatar/girl_1.png'),
summary: '看看这些电影吧...', likes: 800,
avatar: require('@/assets/default-avatar/girl_1.png'), comments: 5,
likes: 800, favorites: 50,
comments: 5, },
favorites: 50, {
}, id: 3,
{ category: '二手交易',
id: 3, title: '出售二手书籍',
category: '二手交易', summary: '价格优惠,欢迎咨询...',
title: '出售二手书籍', avatar: require('@/assets/default-avatar/boy_2.png'),
summary: '价格优惠,欢迎咨询...', likes: 300,
avatar: require('@/assets/default-avatar/boy_2.png'), comments: 2,
likes: 300, favorites: 20,
comments: 2, },
favorites: 20, {
}, id: 4,
{ category: '学习',
id: 4, title: '考研经验分享',
category: '学习', summary: '考研路上的一些心得...',
title: '考研经验分享', avatar: require('@/assets/default-avatar/girl_3.png'),
summary: '考研路上的一些心得...', likes: 1500,
avatar: require('@/assets/default-avatar/girl_3.png'), comments: 20,
likes: 1500, favorites: 200,
comments: 20, },
favorites: 200, ]);
},
]); const filteredPosts = ref(posts.value);
const filteredPosts = ref(posts.value); const router = useRouter();
const router = useRouter();
const selectCategory = (category) => { const selectCategory = (category) => {
selectedCategory.value = category; selectedCategory.value = category;
filteredPosts.value = filteredPosts.value =
category === '全部' category === '全部'
? posts.value ? posts.value
: posts.value.filter((post) => post.category === category); : posts.value.filter((post) => post.category === category);
}; };
const goToPostDetail = (postId) => { const goToPostDetail = (postId) => {
router.push({ name: 'PostDetail', params: { id: postId } }); router.push({ name: 'PostDetail', params: { id: postId } });
};
return {
categories,
selectedCategory,
filteredPosts,
selectCategory,
goToPostDetail,
};
},
}; };
</script> </script>

@ -90,207 +90,184 @@
</div> </div>
</template> </template>
<script> <script setup lang="js" name="UserRegister">
import { ref, computed, onMounted } from 'vue'; import { ref, computed, onMounted } from 'vue';
import request from '@/utils/request'; import request from '@/utils/request';
import {ElMessage} from 'element-plus' import { ElMessage } from 'element-plus';
export default { const emit = defineEmits(['toggleForm']);
name: 'UserRegister',
setup(props, { emit }) { const currentType = ref('username');
const currentType = ref('username'); const cooldown = ref(0); //
const cooldown = ref(0); //
//
// const registerTypes = [
const registerTypes = [ { label: '用户名注册', value: 'username' },
{ label: '用户名注册', value: 'username' }, { label: '邮箱注册', value: 'email' },
{ label: '邮箱注册', value: 'email' }, { label: '手机注册', value: 'phone' }
{ label: '手机注册', value: 'phone' } ];
];
//
// const registerForm = ref({
const registerForm = ref({ username: '',
username: '', email: '',
email: '', phone: '',
phone: '', password: '',
password: '', confirmPassword: '',
confirmPassword: '', verifyCode: '', // (/)
verifyCode: '', //(/) captcha: '' //
captcha: '' // });
});
//
// const isValidInput = computed(() => {
const isValidInput = computed(() => { const value = registerForm.value[currentType.value];
const value = registerForm.value[currentType.value] if (!value) return false;
if (!value) return false switch (currentType.value) {
case 'email':
return /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value);
case 'phone':
return /^1[3-9]\d{9}$/.test(value);
default:
return false;
}
});
switch(currentType.value) { // URL
case 'email': const captchaUrl = ref('/user/captcha');
return /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)
case 'phone':
return /^1[3-9]\d{9}$/.test(value)
default:
return false
}
})
//URL
const captchaUrl = ref('/user/captcha');
//
const inputType = computed(() => {
switch(currentType.value) {
case 'email': return 'email';
case 'phone': return 'tel';
default: return 'text';
}
});
// //
const placeholder = computed(() => { const inputType = computed(() => {
switch(currentType.value) { switch (currentType.value) {
case 'email': return '请输入邮箱'; case 'email': return 'email';
case 'phone': return '请输入手机号'; case 'phone': return 'tel';
default: return '请输入用户名'; default: return 'text';
} }
});
//
const placeholder = computed(() => {
switch (currentType.value) {
case 'email': return '请输入邮箱';
case 'phone': return '请输入手机号';
default: return '请输入用户名';
}
});
// /
const showVerifyCode = computed(() => {
return ['email', 'phone'].includes(currentType.value);
});
// /使
async function sendCode() {
if (cooldown.value > 0 || !isValidInput.value) return;
try {
// TODO
const response = await request.post(`/user/send-code`, {
type: currentType.value,
target: registerForm.value[currentType.value]
}); });
/// if (response.success) {
const showVerifyCode = computed(() => { ElMessage({
return ['email', 'phone'].includes(currentType.value); message: '验证码已发送',
}); type: 'info'
});
// /使 // 60
async function sendCode() { cooldown.value = 60;
if (cooldown.value > 0 || !isValidInput.value) return; const timer = setInterval(() => {
cooldown.value--;
try { if (cooldown.value <= 0) {
//TODO clearInterval(timer);
const response = await request.post(`/user/send-code`, {
type: currentType.value,
target: registerForm.value[currentType.value]
});
if (response.success) {
ElMessage({
message: '验证码已发送',
type: 'info'
});
// 60
cooldown.value = 60;
const timer = setInterval(() => {
cooldown.value--;
if (cooldown.value <= 0) {
clearInterval(timer);
}
}, 1000);
} }
} catch (error) { }, 1000);
console.error('发送验证码失败:', error);
alert('发送验证码失败,请稍后重试');
}
} }
} catch (error) {
console.error('发送验证码失败:', error);
alert('发送验证码失败,请稍后重试');
}
}
//
function refreshCaptcha() {
//
captchaUrl.value = `/user/captcha?t=${new Date().getTime()}`;
}
//
async function register() {
try {
//
const captchaResponse = await request.post('/user/verify-captcha', {
captcha: registerForm.value.captcha
});
// if (captchaResponse.code !== 200) {
function refreshCaptcha() { ElMessage({
// message: captchaResponse.msg,
captchaUrl.value = `/user/captcha?t=${new Date().getTime()}`; type: 'error',
duration: 500
});
refreshCaptcha();
return;
} }
//TODO:/ //
// if (registerForm.value.password !== registerForm.value.confirmPassword) {
async function register() { ElMessage({
try { message: '两次输入的密码不一致',
// type: 'error',
const captchaResponse = await request.post('/user/verify-captcha', { duration: 500
captcha: registerForm.value.captcha
}); });
return;
}
//
const registerData = {
username: registerForm.value.username,
password: registerForm.value.password
};
if (captchaResponse.code !== 200) { //
ElMessage({ switch (currentType.value) {
message: captchaResponse.msg, case 'email':
type: 'error', registerData.email = registerForm.value.email;
duration: 500 break;
}); case 'phone':
refreshCaptcha(); registerData.phone = registerForm.value.phone;
return; break;
}
//
if (registerForm.value.password !== registerForm.value.confirmPassword) {
ElMessage({
message: '两次输入的密码不一致',
type: 'error',
duration: 500
});
return;
}
//
const registerData = {
username: registerForm.value.username,
password: registerForm.value.password
};
//
switch (currentType.value) {
case 'email':
registerData.email = registerForm.value.email;
break;
case 'phone':
registerData.phone = registerForm.value.phone;
break;
}
const response = await request.post('/user/register', registerData);
if (response.code === 200) {
ElMessage({
message: '注册成功',
type: 'success',
duration: 500
});
//
emit('toggleForm');
} else {
ElMessage({
message: '注册失败,请稍后重试',
type: 'error',
duration: 500
});
}
}
catch (error) {
console.error('注册失败:', error);
alert(error.response?.message || '注册失败,请稍后重试');
refreshCaptcha();
}
} }
onMounted(() => { const response = await request.post('/user/register', registerData);
//
refreshCaptcha();
});
// 使 if (response.code === 200) {
return { ElMessage({
currentType, message: '注册成功',
registerTypes, type: 'success',
registerForm, duration: 500
captchaUrl, });
inputType, //
placeholder, emit('toggleForm');
showVerifyCode, } else {
cooldown, ElMessage({
sendCode, message: '注册失败,请稍后重试',
refreshCaptcha, type: 'error',
register, duration: 500
isValidInput });
}; }
}
catch (error) {
console.error('注册失败:', error);
alert(error.response?.message || '注册失败,请稍后重试');
refreshCaptcha();
} }
} }
onMounted(() => {
//
refreshCaptcha();
});
</script> </script>
<style scoped> <style scoped>

@ -31,52 +31,39 @@
</div> </div>
</template> </template>
<script> <script setup lang="js" name="WelcomeCalendar">
import { ref } from 'vue'; import { ref } from 'vue';
export default { const today = new Date();
name: 'WelcomeCalendar',
setup() { //
const today = new Date(); const currentMonthText = ref(['一', '月']); //
const currentDay = ref(today.getDate()); //
// const currentWeekday = ref(['星', '期', '日']); //
const currentMonthText = ref(['一', '月']); //
const currentDay = ref(today.getDate()); // //
const currentWeekday = ref('星','期','日'); // const isCheckedIn = ref(false);
// //
const isCheckedIn = ref(false); const initializeDate = () => {
const months = [
// '一月', '二月', '三月', '四月', '五月', '六月',
const initializeDate = () => { '七月', '八月', '九月', '十月', '十一月', '十二月',
const months = [ ];
'一月', '二月', '三月', '四月', '五月', '六月', const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
'七月', '八月', '九月', '十月', '十一月', '十二月',
]; currentMonthText.value = months[today.getMonth()].split('');
const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']; currentDay.value = today.getDate();
currentWeekday.value = weekdays[today.getDay()].split('');
currentMonthText.value = months[today.getMonth()].split('');
currentDay.value = today.getDate();
currentWeekday.value = weekdays[today.getDay()].split('');
};
//
const checkIn = () => {
isCheckedIn.value = true;
};
//
initializeDate();
return {
currentMonthText,
currentDay,
currentWeekday,
isCheckedIn,
checkIn,
};
},
}; };
//
const checkIn = () => {
isCheckedIn.value = true;
};
//
initializeDate();
</script> </script>
<style scoped> <style scoped>

@ -95,7 +95,7 @@
</div> </div>
</template> </template>
<script setup> <script setup lang ="js" name="FeedBack">
import { ref, reactive } from 'vue' import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus' import { ElMessage } from 'element-plus'

@ -15,21 +15,12 @@
</div> </div>
</template> </template>
<script> <script setup lang="js" name="MainPage">
import NoticeBoard from '@/components/NoticeBoard.vue'; import NoticeBoard from '@/components/NoticeBoard.vue';
import WelcomeCalendar from '@/components/WelcomeCalendar.vue'; import WelcomeCalendar from '@/components/WelcomeCalendar.vue';
import PostPage from '@/components/PostPage.vue'; import PostPage from '@/components/PostPage.vue';
//import UserPage from './UserPage.vue'; // import UserPage from './UserPage.vue';
// import PostDetail from './PostDetail.vue'; // import PostDetail from './PostDetail.vue';
export default {
components: {
NoticeBoard,
WelcomeCalendar,
PostPage,
//UserPage,
// PostDetail
}
};
</script> </script>
<style scoped> <style scoped>

@ -19,40 +19,39 @@
</div> </div>
</template> </template>
<script> <script setup lang="js" name="NotificationDetail">
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
const route = useRoute();
const currentNotice = ref(null);
const errorMessage = ref('');
//
const mockFetchNotice = (id) => { const mockFetchNotice = (id) => {
return new Promise((resolve) => { return new Promise((resolve) => {
setTimeout(() => { setTimeout(() => {
const notices = [ const notices = [
{ id: 1, title: "系统维护通知", /* 其他字段 */ }, { id: 1, title: "系统维护通知", time: "2024-05-01 10:00", content: "系统将于今晚23:00-24:00进行维护请提前保存数据。" },
{ id: 2, title: "新功能上线", /* 其他字段 */ } { id: 2, title: "新功能上线", time: "2024-05-10 09:00", content: "我们上线了新功能,欢迎体验!" }
] ];
resolve(notices.find(n => n.id === Number(id))) resolve(notices.find(n => n.id === Number(id)));
}, 500) }, 500);
}) });
} };
export default { onMounted(async () => {
props: ['id'], // props try {
data() { const data = await mockFetchNotice(route.params.id);
return { if (data) {
currentNotice: null, currentNotice.value = data;
errorMessage: '' } else {
} errorMessage.value = '通知不存在';
},
async created() {
try {
const data = await mockFetchNotice(this.id)
if (data) {
this.currentNotice = data
} else {
this.errorMessage = '通知不存在'
}
} catch (error) {
this.errorMessage = '加载失败,请稍后重试'
} }
} catch (error) {
errorMessage.value = '加载失败,请稍后重试';
} }
} });
</script> </script>
<style scoped> <style scoped>

@ -18,34 +18,32 @@
</div> </div>
</template> </template>
<script> <script setup lang="js" name="NotificationList">
export default { import { ref } from 'vue';
data() { import { useRouter } from 'vue-router';
return {
notifications: [ const router = useRouter();
{
id:1, const notifications = ref([
title: "系统维护通知", {
time: "2023-08-20 14:00", id: 1,
content: "服务器将于今晚24:00进行例行维护预计持续2小时" title: "系统维护通知",
}, time: "2023-08-20 14:00",
{ content: "服务器将于今晚24:00进行例行维护预计持续2小时"
id:2,
title: "新功能上线",
time: "2023-08-19 09:30",
content: "消息中心新增批量处理功能,欢迎体验"
}
]
}
}, },
methods: { {
viewDetail(noticeId) { id: 2,
this.$router.push({ title: "新功能上线",
name: 'NotificationDetail', time: "2023-08-19 09:30",
params: { id: noticeId } // content: "消息中心新增批量处理功能,欢迎体验"
})
}
} }
]);
function viewDetail(noticeId) {
router.push({
name: 'NotificationDetail',
params: { id: noticeId }
});
} }
</script> </script>

@ -57,92 +57,74 @@
</div> </div>
</template> </template>
<script> <script setup lang="js" name="PostDetail">
import { ref, onMounted } from 'vue'; import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router'; import { useRoute } from 'vue-router';
export default { const route = useRoute();
name: 'PostDetail', const postId = ref(route.params.id);
setup() { const postTitle = ref('');
const route = useRoute(); const postContent = ref('');
const postId = ref(route.params.id); const newComment = ref('');
const postTitle = ref('');
const postContent = ref(''); //
const newComment = ref(''); const author = ref({
avatar: require('@/assets/default-avatar/boy_4.png'),
// name: '珈人1号',
const author = ref({ followers: 1234,
avatar: require('@/assets/default-avatar/boy_4.png'), });
name: '珈人1号',
followers: 1234, //
}); const postStats = ref({
likes: 1200,
// favorites: 300,
const postStats = ref({ comments: 45,
likes: 1200, });
favorites: 300,
comments: 45, //
}); const postTime = ref('2025年4月20日 14:30');
// //
const postTime = ref('2025年4月20日 14:30'); const comments = ref([
{
// avatar: require('@/assets/default-avatar/girl_1.png'),
const comments = ref([ name: '评论者1',
{ text: '这是第一条评论。',
avatar: require('@/assets/default-avatar/girl_1.png'), time: '2025年4月20日 15:00',
name: '评论者1', // likes: 10,
text: '这是第一条评论。', },
time: '2025年4月20日 15:00', {
likes: 10, avatar: require('@/assets/default-avatar/boy_2.png'),
}, name: '评论者2',
{ text: '这是第二条评论。',
avatar: require('@/assets/default-avatar/boy_2.png'), time: '2025年4月20日 15:30',
name: '评论者2', // likes: 5,
text: '这是第二条评论。', },
time: '2025年4月20日 15:30', ]);
likes: 5,
}, const isFollowing = ref(false);
]);
const toggleFollow = () => {
const isFollowing = ref(false); isFollowing.value = !isFollowing.value;
const toggleFollow = () => {
isFollowing.value = !isFollowing.value;
};
const sendComment = () => {
if (newComment.value.trim()) {
comments.value.push({
avatar: require('@/assets/default-avatar/boy_1.png'),
name: '新评论者', //
text: newComment.value,
time: new Date().toLocaleString(),
likes: 0,
});
newComment.value = '';
}
};
onMounted(() => {
postTitle.value = `帖子标题 ${postId.value}`;
postContent.value = `这是帖子 ${postId.value} 的内容,展示帖子的详细信息。`;
});
return {
postTitle,
postContent,
comments,
newComment,
sendComment,
author,
postStats,
postTime,
isFollowing,
toggleFollow,
};
},
}; };
const sendComment = () => {
if (newComment.value.trim()) {
comments.value.push({
avatar: require('@/assets/default-avatar/boy_1.png'),
name: '新评论者',
text: newComment.value,
time: new Date().toLocaleString(),
likes: 0,
});
newComment.value = '';
}
};
onMounted(() => {
postTitle.value = `帖子标题 ${postId.value}`;
postContent.value = `这是帖子 ${postId.value} 的内容,展示帖子的详细信息。`;
});
</script> </script>
<style scoped> <style scoped>

@ -57,39 +57,32 @@
</div> </div>
</template> </template>
<script> <script setup lang="js" name="UserPage">
import { ref } from 'vue'; import { ref } from 'vue';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
export default {
name: 'UserPage', const posts = ref([
setup() { {
const posts = ref([ id: 1,
{ title: '雷霆连续两场或20分钟逆转什么水平',
id:1, summary: '今天保罗带领雷霆完成逆转',
title: '雷霆连续两场或20分钟逆转什么水平', likes: 1200,
summary: '今天保罗带领雷霆完成逆转', comments: 10,
likes: 1200, favorites: 100,
comments: 10, },
favorites: 100, {
}, id: 2,
{ title: '一个普通人需要多大努力才能考上985',
id:2, summary: 'mmmmmmmm',
title: '一个普通人需要多大努力才能考上985', likes: 2200,
summary: 'mmmmmmmm', comments: 20,
likes: 2200, favorites: 200,
comments: 20,
favorites: 200,
},
]);
const router = useRouter();
const goToPostDetail = (postId) => {
router.push({ name: 'PostDetail', params: { id: postId } });
};
return {
posts,
goToPostDetail,
};
}, },
]);
const router = useRouter();
const goToPostDetail = (postId) => {
router.push({ name: 'PostDetail', params: { id: postId } });
}; };
</script> </script>

Loading…
Cancel
Save