ES6中,開始支持模板字元串。 儘管Java和C#這樣的高級語言有非常多吸引人的地方,但是想js這樣的弱類型語言,也有獨到之處。 equType:有四種類型,分別是:chl、chwp、cwp、cot,後端java介面提供了四個介面,四個介面對應四個函數調用,每一個函數名的規則是[equType]Co ...
ES6中,開始支持模板字元串。
儘管Java和C#這樣的高級語言有非常多吸引人的地方,但是想js這樣的弱類型語言,也有獨到之處。
equType:有四種類型,分別是:chl、chwp、cwp、cot,後端java介面提供了四個介面,四個介面對應四個函數調用,每一個函數名的規則是[equType]Control,
let equDetailService = {*/ chlControl: function(params) { return request.post(url.coldStation.equDetail.chlControl, params); }, //冷凍泵啟停介面 chwpControl: function(params) { return request.post(url.coldStation.equDetail.chwpControl, params); }, //冷卻泵啟停介面 cwpControl: function(params) { return request.post(url.coldStation.equDetail.cwpControl, params); }, //冷卻塔啟停介面 cotControl: function(params) { return request.post(url.coldStation.equDetail.cotControl, params); } };
前端同一個組件在四個不同的頁面中使用,組件對應的equType值不同,根據equType值不同要調用後端不同的介面。
axios的js調用:
equDetailService[`${this.equType}Control`](serachObj).then(res => { if (res.code === 200) { //執行成功 } });
後端一個詳情頁面的介面返回一個Json對象,如下數據:
detailInfo:{G1_COT1_ON/OFF: "0.0", G1_COT1_VFD_ON/OFF: "1.0", G1_COT1_FRQ: "30.0", G1_COT1_FRQ_SET: "50.0", G1_COT1_PWR: "5.0", G1_COT1_PWR_deviceId: 95 G1_COT1_VFD_PWR: "5.0", G1_COT1_VFD_PWR_deviceId: 95 G1_COT1_VFD_ALM: "0.0", G1_COT1_PWR_ALM: "0.0", G1_COT1_PWR_ALM_deviceId: 95, G1_COT1_REM/LOC: "1.0", G1_COT1_HRS: "5300.0", G1_COT1_EN/DIS: "1.0", G1_COT1_RANK: "0.0", G1_COT1_PWR_FRQ: "0.0", G1_COT1_PWR_FRQ_deviceId: 95, G1_COT1_FRQ_HAND/AUTO: "0.0", G1_COT2_ON/OFF: "0.0", G1_COT2_VFD_ON/OFF: "1.0", G1_COT2_FRQ: "30.0", G1_COT2_FRQ_SET: "50.0", G1_COT2_PWR: "5.0", G1_COT2_PWR_deviceId: 96, G1_COT2_VFD_PWR: "5.0", G1_COT2_VFD_PWR_deviceId: 96, G1_COT2_VFD_ALM: "0.0", G1_COT2_PWR_ALM: "0.0", G1_COT2_PWR_ALM_deviceId: 96, G1_COT2_REM/LOC: "1.0", G1_COT2_HRS: "5437.0", G1_COT2_EN/DIS: "1.0", G1_COT2_RANK: "0.0", G1_COT2_PWR_FRQ: "--", G1_COT2_PWR_FRQ_deviceId: 96, G1_COT2_FRQ_HAND/AUTO: "0.0", G1_COT3_ON/OFF: "0.0", G1_COT3_VFD_ON/OFF: "1.0", G1_COT3_FRQ: "30.0", G1_COT3_FRQ_SET: "50.0", G1_COT3_PWR: "5.0", G1_COT3_PWR_deviceId: 97, G1_COT3_VFD_PWR: "5.0", G1_COT3_VFD_PWR_deviceId: 97, G1_COT3_VFD_ALM: "0.0", G1_COT3_PWR_ALM: "0.0", G1_COT3_PWR_ALM_deviceId: 97, G1_COT3_REM/LOC: "1.0", G1_COT3_HRS: "5436.0", G1_COT3_EN/DIS: "1.0", G1_COT3_RANK: "0.0", G1_COT3_PWR_FRQ: "--", G1_COT3_PWR_FRQ_deviceId: 97, G1_COT3_FRQ_HAND/AUTO: "1.0",
}
G1是組名,groupNumber會變化,
而前端又是一個組件,好幾個頁面用,只調用一個介面,介面返回的是個Json對象,而不是一個數組,但是前端界面又要顯示三個tab,進行數據綁定時,又可以用到模板字元,以取G1_COT1_FRQ_SET這個字元為例,vue數據綁定:
{{detailInfo[`${groupNumber}_COT${index+1}_FRQ_SET`]}}
直接可以把detailInfo中的數據拆分為3項。
Java有的語法糖,JS有,Java沒有的語法糖,JS還是有,這就是它的強大之處。
總結:模板字元在有些時候可以避免if else和正則表達式校驗,類似於後端語言的反射(如C#)。註:一些高級語言的反射非常耗性能。