遵循了从元信息 → 输入 → 输出 → 内部逻辑 → 副作用 的思维流程,代码可读性最好
java
<script setup>
// 1. 组件元信息
defineOptions({
name: 'ComponentName',
inheritAttrs: false,
// ...
})
// 2. Props 定义
const props = defineProps({
modelValue: String,
// ...
})
// 3. Emits 定义
const emit = defineEmits(['update:modelValue', 'change'])
// 4. Expose 定义(暴露给父组件的方法/数据)
defineExpose({
refresh,
validate
})
// 5. 导入语句(虽然可以在顶部,但放这里更符合逻辑流)
import { ref, computed, watch, onMounted } from 'vue'
// 6. Store 相关
const appStore = useAppStore()
// 7. 路由相关
const route = useRoute()
const router = useRouter()
// 8. 响应式数据(按重要性排序)
const loading = ref(false)
const list = ref([])
const form = reactive({ name: '', age: 0 })
// 9. 计算属性
const computedData = computed(() => { /* ... */ })
const filteredList = computed(() => list.value.filter(/* ... */))
// 10. 侦听器
watch(() => props.modelValue, (newVal) => { /* ... */ })
watchEffect(() => { /* ... */ })
// 11. 生命周期钩子(按执行顺序)
onBeforeMount(() => { /* ... */ })
onMounted(() => { /* ... */ })
onBeforeUnmount(() => { /* ... */ })
// 12. 方法(按逻辑分组)
// 12.1 初始化方法
async function initData() { /* ... */ }
// 12.2 事件处理
function handleClick() { /* ... */ }
function onSubmit() { /* ... */ }
// 12.3 API 调用
async function fetchData() { /* ... */ }
// 12.4 工具方法
function validate() { /* ... */ }
function reset() { /* ... */ }
</script>