Nuxt项目使用Composables时首次加载页面耗时过长问题
Nuxt项目中使用Composables导致页面首次加载耗时过长
在Nuxt项目里,所有页面首次打开时加载速度都很慢。以登录页为例,当我把所有登录相关功能封装在useLogin Composable中时,首次进入页面会有明显延迟;但把功能代码直接写在登录页内部时,加载性能有显著提升。
使用useLogin Composable的登录页代码
<script setup> definePageMeta({ layout: "custom", middleware: "login", }); useHead({ title: "登录", meta: [ { name: "description", content: "登录", }, ], }); const { email, password, login } = useLogIn() </script>
对应的useLogin Composable代码
export default function autorization() { const toast = useToast(); const email = ref(""); const password = ref(""); const token = useToken(); const { public: { apiBase }, } = useRuntimeConfig(); const login = async () => { try { if (email.value === "" || password.value === "") { toast.add({ title: "请填写所有字段", color: "yellow" }); return; } const response = await $fetch(`${apiBase}/user/login`, { params: { login: email.value, password: password.value, }, }); if (response.isVerify) { token.value = `Bearer ${response.token}`; console.log("登录成功"); navigateTo("/"); } } catch (error) { console.error("登录错误: ", error.response); try { if (error.response._data.message === "用户名或密码错误") { toast.add({ title: "用户名或密码错误", color: "red" }); } } catch (error) { toast.add({ title: "发生未知错误", color: "red" }); } } }; return { email, password, login, }; }
首次进入该页面时的延迟情况截图:
功能直接写在登录页内的代码
<script setup> definePageMeta({ layout: "custom", middleware: "login", }); useHead({ title: "登录", meta: [ { name: "description", content: "登录", }, ], }); const toast = useToast(); const email = ref(""); const password = ref(""); const token = useToken(); const { public: { apiBase }, } = useRuntimeConfig(); const login = async () => { try { if (email.value === "" || password.value === "") { toast.add({ title: "请填写所有字段", color: "yellow" }); return; } const response = await $fetch(`${apiBase}/user/login`, { params: { login: email.value, password: password.value, }, }); if (response.isVerify) { token.value = `Bearer ${response.token}`; console.log("登录成功"); navigateTo("/"); } } catch (error) { console.error("登录错误: ", error.response); try { if (error.response._data.message === "用户名或密码错误") { toast.add({ title: "用户名或密码错误", color: "red" }); } } catch (error) { toast.add({ title: "发生未知错误", color: "red" }); } } }; </script>
两种实现方式的性能差异对比截图:
内容的提问来源于stack exchange,提问作者Rudee Sayuki
相关产品推荐
相关产品推荐

