Nuxt Composition API生命周期、变量与函数编写顺序最佳实践咨询
Nuxt Composition API 代码编写顺序规范
针对团队协作中遇到的代码顺序疑问,统一以下规范,让代码更整洁、评审更高效:
1. 导入顺序优化
当前代码的导入逻辑比较零散,建议按「核心API → 工具函数 → 项目常量 → UI组件」的层级排序,符合代码依赖的递进关系:
调整后的导入示例:
<script> // 1. 先导入Nuxt Composition API核心方法 import { computed, onMounted, ref} from '@nuxtjs/composition-api'; // 2. 再导入项目工具函数 import { allNotificationsMarkAsRead } from '@/common/firebase/notificationsHelper'; import { getCached } from '@/common/cache'; // 3. 接着导入项目常量 import { contentTypes, resizeSize } from '../constants'; // 4. 最后导入UI组件 import CmIcon from '@/components/icon/cm-icon'; import CmCommentCard from '@/components/cards/notification-card/cm-comment-card'; </script>
理由:从基础框架API到业务工具,再到固定常量,最后是UI组件,阅读时能快速定位不同类型的导入,逻辑链条更清晰。
2. setup函数内:ref 优先于 computed 编写
建议先定义响应式原始状态(ref/reactive),再写派生状态(computed)。因为computed的值依赖于ref/reactive的原始状态,先看基础数据再看计算结果,符合认知逻辑,也方便后续修改状态时快速找到关联的computed。
调整后的setup示例:
setup(){ const { app, route, store, redirect, error } = useContext(); const { newsDetailMetaTagData } = newsDetailMetaTag(); const { setModalData, modalData, getModalData, galleryModalDetail } = useModal(); const headlineClient = app.apolloProvider.clients.headline; const router = useRouter(); // 1. 先定义响应式原始状态 const detailedContent = ref([]); const modalRef = ref(null); // 2. 再定义基于原始状态的computed const activeOrder = computed(() => store.state['detailPages'].activeOrder); const categoryName = computed(() => route.value.params.category); }
3. 生命周期钩子与自定义函数:先函数,后钩子
建议先编写自定义工具函数,再写生命周期钩子。因为生命周期钩子内部通常会调用这些自定义函数,先看函数定义再看使用场景,不用来回跳转查找代码。
调整后的示例:
// 1. 先定义自定义函数 const finishMounting = () => { isMounting.value = false; }; const logCountText = () => { console.log(document.getElementById('count').textContent); }; // 2. 再写生命周期钩子,调用已定义的函数 onMounted(() => { finishMounting(); }); onUpdated(() => { logCountText(); });
如果是生命周期内的简单逻辑,也可以直接写在钩子内部,但逻辑复杂或需要复用时,一定要先抽成独立函数再调用,这样结构更清晰,也方便后续复用和测试。
内容的提问来源于stack exchange,提问作者oktay tontaş
相关产品推荐
相关产品推荐

