重构已有前端代码

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 = () => {
// /
const toggleForm = () => {
isLogin.value = !isLogin.value; isLogin.value = !isLogin.value;
}; };
return { //
isLogin, const close = () => {
toggleForm, emit('close');
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',
setup() {
const images = ref([
{ src: require('@/assets/whu1.jpg'), alt: '公告图片1' }, { src: require('@/assets/whu1.jpg'), alt: '公告图片1' },
{ src: require('@/assets/whu2.jpg'), alt: '公告图片2' }, { src: require('@/assets/whu2.jpg'), alt: '公告图片2' },
{ src: require('@/assets/whu3.jpg'), alt: '公告图片3' }, { src: require('@/assets/whu3.jpg'), alt: '公告图片3' },
{ src: require('@/assets/whu4.jpg'), alt: '公告图片4' }, { src: require('@/assets/whu4.jpg'), alt: '公告图片4' },
{ src: require('@/assets/whu5.jpg'), alt: '公告图片5' }, { src: require('@/assets/whu5.jpg'), alt: '公告图片5' },
]); ]);
const currentIndex = ref(0); const currentIndex = ref(0);
// //
const nextImage = () => { const nextImage = () => {
currentIndex.value = (currentIndex.value + 1) % images.value.length; currentIndex.value = (currentIndex.value + 1) % images.value.length;
}; };
// //
const prevImage = () => { const prevImage = () => {
currentIndex.value = currentIndex.value =
(currentIndex.value - 1 + images.value.length) % images.value.length; (currentIndex.value - 1 + images.value.length) % images.value.length;
}; };
// //
const goToImage = (index) => { const goToImage = (index) => {
currentIndex.value = index; currentIndex.value = index;
}; };
// //
let interval = null; let interval = null;
onMounted(() => { onMounted(() => {
//
interval = setInterval(nextImage, 5000); interval = setInterval(nextImage, 5000);
}); });
onUnmounted(() => { onUnmounted(() => {
//
clearInterval(interval); clearInterval(interval);
}); });
return {
images,
currentIndex,
nextImage,
prevImage,
goToImage,
};
},
};
</script> </script>
<style scoped> <style scoped>

@ -36,15 +36,13 @@
</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, id: 1,
category: '学习', category: '学习',
@ -85,30 +83,22 @@ export default {
comments: 20, comments: 20,
favorites: 200, favorites: 200,
}, },
]); ]);
const filteredPosts = ref(posts.value);
const router = useRouter();
const filteredPosts = ref(posts.value); const selectCategory = (category) => {
const router = useRouter();
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,82 +90,79 @@
</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 cooldown = ref(0); //
// const currentType = ref('username');
const registerTypes = [ const cooldown = ref(0); //
//
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) {
switch(currentType.value) {
case 'email': case 'email':
return /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value) return /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value);
case 'phone': case 'phone':
return /^1[3-9]\d{9}$/.test(value) return /^1[3-9]\d{9}$/.test(value);
default: default:
return false return false;
} }
}) });
//URL // URL
const captchaUrl = ref('/user/captcha'); const captchaUrl = ref('/user/captcha');
// //
const inputType = computed(() => { const inputType = computed(() => {
switch(currentType.value) { switch (currentType.value) {
case 'email': return 'email'; case 'email': return 'email';
case 'phone': return 'tel'; case 'phone': return 'tel';
default: return 'text'; default: return 'text';
} }
}); });
// //
const placeholder = computed(() => { const placeholder = computed(() => {
switch(currentType.value) { switch (currentType.value) {
case 'email': return '请输入邮箱'; case 'email': return '请输入邮箱';
case 'phone': return '请输入手机号'; case 'phone': return '请输入手机号';
default: return '请输入用户名'; default: return '请输入用户名';
} }
}); });
/// // /
const showVerifyCode = computed(() => { const showVerifyCode = computed(() => {
return ['email', 'phone'].includes(currentType.value); return ['email', 'phone'].includes(currentType.value);
}); });
// /使 // /使
async function sendCode() { async function sendCode() {
if (cooldown.value > 0 || !isValidInput.value) return; if (cooldown.value > 0 || !isValidInput.value) return;
try { try {
//TODO // TODO
const response = await request.post(`/user/send-code`, { const response = await request.post(`/user/send-code`, {
type: currentType.value, type: currentType.value,
target: registerForm.value[currentType.value] target: registerForm.value[currentType.value]
@ -190,17 +187,16 @@ export default {
console.error('发送验证码失败:', error); console.error('发送验证码失败:', error);
alert('发送验证码失败,请稍后重试'); alert('发送验证码失败,请稍后重试');
} }
} }
// //
function refreshCaptcha() { function refreshCaptcha() {
// //
captchaUrl.value = `/user/captcha?t=${new Date().getTime()}`; captchaUrl.value = `/user/captcha?t=${new Date().getTime()}`;
} }
//TODO:/ //
// async function register() {
async function register() {
try { try {
// //
const captchaResponse = await request.post('/user/verify-captcha', { const captchaResponse = await request.post('/user/verify-captcha', {
@ -217,7 +213,7 @@ export default {
return; return;
} }
// //
if (registerForm.value.password !== registerForm.value.confirmPassword) { if (registerForm.value.password !== registerForm.value.confirmPassword) {
ElMessage({ ElMessage({
message: '两次输入的密码不一致', message: '两次输入的密码不一致',
@ -251,7 +247,7 @@ export default {
type: 'success', type: 'success',
duration: 500 duration: 500
}); });
// //
emit('toggleForm'); emit('toggleForm');
} else { } else {
ElMessage({ ElMessage({
@ -260,37 +256,18 @@ export default {
duration: 500 duration: 500
}); });
} }
} }
catch (error) { catch (error) {
console.error('注册失败:', error); console.error('注册失败:', error);
alert(error.response?.message || '注册失败,请稍后重试'); alert(error.response?.message || '注册失败,请稍后重试');
refreshCaptcha(); refreshCaptcha();
} }
} }
onMounted(() => { onMounted(() => {
// //
refreshCaptcha(); refreshCaptcha();
}); });
// 使
return {
currentType,
registerTypes,
registerForm,
captchaUrl,
inputType,
placeholder,
showVerifyCode,
cooldown,
sendCode,
refreshCaptcha,
register,
isValidInput
};
}
}
</script> </script>
<style scoped> <style scoped>

@ -31,24 +31,21 @@
</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 currentMonthText = ref(['一', '月']); //
const currentDay = ref(today.getDate()); // const currentDay = ref(today.getDate()); //
const currentWeekday = ref('星','期','日'); // const currentWeekday = ref(['星', '期', '日']); //
// //
const isCheckedIn = ref(false); const isCheckedIn = ref(false);
// //
const initializeDate = () => { const initializeDate = () => {
const months = [ const months = [
'一月', '二月', '三月', '四月', '五月', '六月', '一月', '二月', '三月', '四月', '五月', '六月',
'七月', '八月', '九月', '十月', '十一月', '十二月', '七月', '八月', '九月', '十月', '十一月', '十二月',
@ -58,25 +55,15 @@ export default {
currentMonthText.value = months[today.getMonth()].split(''); currentMonthText.value = months[today.getMonth()].split('');
currentDay.value = today.getDate(); currentDay.value = today.getDate();
currentWeekday.value = weekdays[today.getDay()].split(''); currentWeekday.value = weekdays[today.getDay()].split('');
}; };
// //
const checkIn = () => { const checkIn = () => {
isCheckedIn.value = true; isCheckedIn.value = true;
};
//
initializeDate();
return {
currentMonthText,
currentDay,
currentWeekday,
isCheckedIn,
checkIn,
};
},
}; };
//
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
data() {
return {
currentNotice: null,
errorMessage: ''
}
},
async created() {
try { try {
const data = await mockFetchNotice(this.id) const data = await mockFetchNotice(route.params.id);
if (data) { if (data) {
this.currentNotice = data currentNotice.value = data;
} else { } else {
this.errorMessage = '通知不存在' errorMessage.value = '通知不存在';
} }
} catch (error) { } catch (error) {
this.errorMessage = '加载失败,请稍后重试' 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();
const notifications = ref([
{ {
id:1, id: 1,
title: "系统维护通知", title: "系统维护通知",
time: "2023-08-20 14:00", time: "2023-08-20 14:00",
content: "服务器将于今晚24:00进行例行维护预计持续2小时" content: "服务器将于今晚24:00进行例行维护预计持续2小时"
}, },
{ {
id:2, id: 2,
title: "新功能上线", title: "新功能上线",
time: "2023-08-19 09:30", time: "2023-08-19 09:30",
content: "消息中心新增批量处理功能,欢迎体验" content: "消息中心新增批量处理功能,欢迎体验"
} }
] ]);
}
}, function viewDetail(noticeId) {
methods: { router.push({
viewDetail(noticeId) {
this.$router.push({
name: 'NotificationDetail', name: 'NotificationDetail',
params: { id: noticeId } // 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({
//
const author = ref({
avatar: require('@/assets/default-avatar/boy_4.png'), avatar: require('@/assets/default-avatar/boy_4.png'),
name: '珈人1号', name: '珈人1号',
followers: 1234, followers: 1234,
}); });
// //
const postStats = ref({ const postStats = ref({
likes: 1200, likes: 1200,
favorites: 300, favorites: 300,
comments: 45, comments: 45,
}); });
// //
const postTime = ref('2025年4月20日 14:30'); const postTime = ref('2025年4月20日 14:30');
// //
const comments = ref([ const comments = ref([
{ {
avatar: require('@/assets/default-avatar/girl_1.png'), avatar: require('@/assets/default-avatar/girl_1.png'),
name: '评论者1', // name: '评论者1',
text: '这是第一条评论。', text: '这是第一条评论。',
time: '2025年4月20日 15:00', time: '2025年4月20日 15:00',
likes: 10, likes: 10,
}, },
{ {
avatar: require('@/assets/default-avatar/boy_2.png'), avatar: require('@/assets/default-avatar/boy_2.png'),
name: '评论者2', // name: '评论者2',
text: '这是第二条评论。', text: '这是第二条评论。',
time: '2025年4月20日 15:30', time: '2025年4月20日 15:30',
likes: 5, likes: 5,
}, },
]); ]);
const isFollowing = ref(false); const isFollowing = ref(false);
const toggleFollow = () => { const toggleFollow = () => {
isFollowing.value = !isFollowing.value; isFollowing.value = !isFollowing.value;
}; };
const sendComment = () => { const sendComment = () => {
if (newComment.value.trim()) { if (newComment.value.trim()) {
comments.value.push({ comments.value.push({
avatar: require('@/assets/default-avatar/boy_1.png'), avatar: require('@/assets/default-avatar/boy_1.png'),
name: '新评论者', // name: '新评论者',
text: newComment.value, text: newComment.value,
time: new Date().toLocaleString(), time: new Date().toLocaleString(),
likes: 0, likes: 0,
}); });
newComment.value = ''; newComment.value = '';
} }
}; };
onMounted(() => { onMounted(() => {
postTitle.value = `帖子标题 ${postId.value}`; postTitle.value = `帖子标题 ${postId.value}`;
postContent.value = `这是帖子 ${postId.value} 的内容,展示帖子的详细信息。`; postContent.value = `这是帖子 ${postId.value} 的内容,展示帖子的详细信息。`;
}); });
return {
postTitle,
postContent,
comments,
newComment,
sendComment,
author,
postStats,
postTime,
isFollowing,
toggleFollow,
};
},
};
</script> </script>
<style scoped> <style scoped>

@ -57,15 +57,13 @@
</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, id: 1,
title: '雷霆连续两场或20分钟逆转什么水平', title: '雷霆连续两场或20分钟逆转什么水平',
summary: '今天保罗带领雷霆完成逆转', summary: '今天保罗带领雷霆完成逆转',
likes: 1200, likes: 1200,
@ -73,23 +71,18 @@ export default {
favorites: 100, favorites: 100,
}, },
{ {
id:2, id: 2,
title: '一个普通人需要多大努力才能考上985', title: '一个普通人需要多大努力才能考上985',
summary: 'mmmmmmmm', summary: 'mmmmmmmm',
likes: 2200, likes: 2200,
comments: 20, comments: 20,
favorites: 200, favorites: 200,
}, },
]); ]);
const router = useRouter();
const goToPostDetail = (postId) => { const router = useRouter();
const goToPostDetail = (postId) => {
router.push({ name: 'PostDetail', params: { id: postId } }); router.push({ name: 'PostDetail', params: { id: postId } });
};
return {
posts,
goToPostDetail,
};
},
}; };
</script> </script>

Loading…
Cancel
Save