如果存在該變量在顯示
<span class="old" v-if="food.oldPrice">¥{{food.oldPrice}}</span>
使用async await 方法 語法糖代替promise then catch
async function myFunction() {
try {
const {code,msg,data} = await somethingThatReturnsAPromise();
if(code === 200 ){
}else{
}
} catch (err) {
console.log(err);
}
}
使用解構獲取對象中的變量
const {phone, code} = this
點擊時間 判斷布爾
@click="loginWay=false"
點擊取反
@click="showPwd=!showPwd"
根據(jù)或關系顯示不同的信息
{{userInfo.phone || '暫無綁定手機號'}}
img加載圖片
<img :src="imgSource" :onerror="default"/>
data(){
return{
imgSource:require('圖片路徑')
default:'this.src="'+require('默認的圖片路徑')+'"'
}
}
使用簡潔的語法
// 邏輯運算符
if (a == 1) {
b()
}
// 可以寫成
a == 1 && b()
// 初始化變量
var a = obj || {}
// 三元運算符
var a = b % 2 == 0 ? 'even' : 'odd'
使用模板字符串
//bad
dom.innerHTML='Hello '
+ name
+ ',How you today?'
//good
dom.innerHTML=`Hello
${name}
How you today?`
合理使用下劃線
doSomeThing(){} //外部調(diào)用接口
_doSomeThing(){} //內(nèi)部調(diào)用接口
變量和常量
const ADD_TODO = 'add_todo' // 使用大寫加下劃線
函數(shù)
const func1 =()=>{} //使用箭頭函數(shù)而不是function xx(){}
取變量 使用解構
const data = {name:'dys', age:1}
const {name = ' ', age = 0} = data //解構給默認值
//
const arr = [1, 2, 3, 4];
// bad
const first = arr[0];
const second = arr[1];
// good
const [first, second] = arr;
使用函數(shù)式編程
//good
function extract(filterFn, mapFn, col) {
return col.filter(filterFn).map(mapFn) //盡量使用filter map reduce
}
//bad
function getData(col) {
var results = []
for (var i = 0; i < col.length; i++) {
if (col[i] && col[i].data) {
results.push(col[i].data)
}
}
return results
}
少寫if else swtich 多用設計模式
使用默認變量替代短路運算或條件
//bad
function createMicrobrewery(name) {
const breweryName = name || 'Hipster Brew Co.'
// ...
}
//good
function createMicrobrewery(breweryName = 'Hipster Brew Co.') {
// ...
}
類型轉化
// good
const val = Number(inputValue);
// good
const totalScore = String(this.reviewScore);
// good
const hasAge = Boolean(age);
注釋
使用 // FIXME: 標注問題
// FIXME: shouldn't use a global here
使用 // TODO: 標注問題的解決方式。
// TODO: total should be configurable by an options param
比較運算符和等號
對象 被計算為 true
Undefined 被計算為 false
Null 被計算為 false
布爾值 被計算為 布爾的值
數(shù)字 如果是 +0、-0、或 NaN 被計算為 false, 否則為 true
字符串 如果是空字符串 '' 被計算為 false,否則為 true
需要回傳多個值時,使用對象解構,而不是數(shù)組解構。
// good
function processInput(input) {
// then a miracle occurs
return { left, right, top, bottom };
}
// 調(diào)用時只選擇需要的數(shù)據(jù)
const { left, right } = processInput(input);
更多參考 這個
優(yōu)化if/else
單一條件判斷 使用 三元表達式
多個單一條件判斷使用swtich case
使用map或者使用多個條件map