前言:遇到类似的功能,更好的做法是封装。
重复代码:一般情况下,遇见重复的功能、逻辑,采用复制代码、粘贴这也是最简单的方式了,但这就是坏味道的开始。 而存在的问题原因就是copy了多次,容易遗漏出未修改的地方,每次迭代还会增加繁琐性。
一、避免重复的HTML结构
遇到重复的结构时,应当封装为组件
badCase:
componentA
<template>
<div>
<button class="primary">按钮</button>
</div>
</template>
componentB
<template>
<div>
<button class="error">按钮</button>
</div>
</template>
goodCase:
<template>
<div>
<button :class="[type]">
<slot />
</button>
</div>
</template>
<script>
export default {
props: {
type: {
type: 'string',
default: 'primary'
}
}
}
</script>
<style>
.primary {
color: 'green'
}
.error {
color: 'red'
}
</style>
二、避免出现重复的逻辑
遇到重复的逻辑时,应当抽离为函数。
badCase:
const userList = [
{
name: "ultraman",
age : 18,
score: 100,
},
{
name: "monsters",
age: 30,
score: 60,
},
];
const getAllUserListScore = () => {
return userList
.map((user) => user.score)
.reduce((acc, score) => (acc += score));
};
const getAllUserListAge = () =>{
return userList
.map((user) => user.age)
.reduce((acc, score) => (acc += score));
}
goodCase:
const getAllTotal = (data, prop) => {
return userList
.map((user) => user[prop])
.reduce((acc, total) => (acc += total));
};
const getAllUserListScore = () => {
return getAllTotal(userList, "score");
};
const getAllUserListAge = () => {
return getAllTotal(userList, "age");
};
三、避免使用过长的条件语句
遇到简单的if的语句时应当换成三元表达式,遇到字符串拼接应该采用模板字符串
badCase:
case1:
if ( a > 1 ) {
this.$message('OK')
} else {
this.$message('Error')
}
case2:
const userAge = 18
const userName = 'ultraman'
const text = '我叫' + userName + ',今年' + userAge + '岁'
goodCase:
case1:
this.$message( a > 1 ? 'OK' : 'Error')
case2:
const userAge = 18
const userName = 'ultraman'
const text = `我叫${userName},今年${userAge}岁`
四、避免硬编码
badCase:
const getDiscountedPrice = (price) => {
return price × 0.8
}
goodCase:
const DISCOUNT_RATE = 0.8
const getDiscountedPrice = (price) => {
return price × DISCOUNT_RATE
}