@author:一勺
- Vue3
- ts
- setup 语法糖
优化前
const isVertical = computed(() => {
if (props.direction === 'vertical') {
return true
} else if (props.direction === 'horizontal') {
return false
}
if (slots && slots.default) {
const vNodes: VNode[] = slots.default()
// 有header或者footer的话,就垂直布局
return vNodes.some((vNode) => {
const tag = (vNode.type as Component).name
return tag === 'YqHeader' || tag === 'YqFooter'
})
}
})
优化后
const isVertical = computed(() => {
// 直接返回props.direction判断结果
if (props.direction === 'vertical') return true
if (props.direction === 'horizontal') return false
// 如果存在默认插槽,检查其中是否有header或footer
const vNodes: VNode[] = slots?.default ? slots.default() : []
// 有header或者footer的话,就垂直布局
return vNodes.some((vNode) => {
const tag = (vNode.type as Component).name
return tag === 'YqHeader' || tag === 'YqFooter'
})
})
思考
- 简化返回逻辑:直接返回判断结果,减少不必要的 if-else 嵌套,提高代码可读性。
- 可选链操作:使用可选链操作符 ?. 来简化对 slots.default 的检查,避免多层检查的繁琐性。
- 移除了不必要的判断:在提取 vNodes 时,如果 slots.default 不存在,直接赋值为空数组,避免后续操作出错。
@author:一勺
- tailwindCSS
- Vue
优化前
<script setup lang="ts"></script>
<template>
<div class="login-view w-[100vw] h-[100vh]"></div>
</template>
<style scoped>
.login-view {
background: url('@/assets/login-bg.svg') no-repeat center center / cover fixed;
}
</style>
优化后
<script setup lang="ts"></script>
<template>
<div
class="bg-[url('@/assets/login-bg.svg')] bg-no-repeat bg-center bg-cover bg-fixed w-screen h-screen"
></div>
</template>
<style scoped></style>
思考
- 原生css最小化
- w-screen / h-screen 代替 w-[100vw] w-[100vh]