我们经常使用if-else判断,代码冗长,可以使用对象配置/策略模式
打折案例:
<template>
<div class="home">
<input type="text" v-model="userkey" />
{{ getcount }}折
</div>
</template>
<script>
export default {
name: "HomeView",
components: {},
data() {
return {
userkey: "",
};
},
computed: {
// 使用if-else判断
// getcount() {
// if (this.userkey == "普通会员") {
// return 0.9;
// } else if (this.userkey == "年费会员") {
// return 0.85;
// } else if (this.userkey == "超级会员") {
// return 0.8;
// } else {
// return 1;
// }
// },
// 使用switch-case判断
// getcount() {
// switch (this.userkey) {
// case "普通会员":
// return 0.9;
// case "年费会员":
// return 0.85;
// case "超级会员":
// return 0.8;
// default:
// return 1;
// // break;
// }
// },
// 对象配置判断
// getcount() {
// let counts = {
// '普通会员':0.9,
// '年费会员':0.85,
// '超级会员':0.8,
// default:1
// }
// return counts[this.userkey]||counts['default']
// }
// map管理键值对
// getcount() {
// var counts = new Map([
// ["普通会员", 0.9],
// ["年费会员", 0.85],
// ["超级会员", 0.8],
// ["default", 1],
// ]);
// return counts.get(this.userkey) || counts.get("default");
// },
},
年终奖案例:
<input type="text" v-model="jixiao" />----绩效-------
<input type="text" v-model="depart" />----部门 <br />
年终奖:{{ getmoney }}元
data() {
return {
jixiao: "",
depart: "",
basemoney: 1000,
};
},
// 绩效A得4倍,B得3倍,C得2倍
// getmoney() {
// let jixiaos = new Map([
// ['A',4],
// ['B',3],
// ['C',2],
// ['default',1]
// ])
// return jixiaos.get(this.jixiao)*this.basemoney ||jixiaos.get('default')*this.basemoney
// }
// 加上部门
// D部门,年终奖翻1.2倍
// F部门,年终奖打折0.9倍
addjixiaopart() {
return this.jixiao + "_" + this.depart;
},
getmoney() {
let jixiaos = new Map([
["A_D", 4 * 1.2],
["B_D", 3 * 1.2],
["C_D", 2 * 1.2],
["A_F", 4 * 0.9],
["B_F", 3 * 0.9],
["C_F", 2 * 0.9],
["default", 1],
]);
return (
jixiaos.get(this.addjixiaopart) * this.basemoney ||
jixiaos.get("default") * this.basemoney
);