Vue 中使用 computed 和 methods 实现 Switch Case 功能
在 Vue 中,可以使用 computed 属性和 methods 方法来实现 switch case 的功能。
1. 使用 computed 属性
computed 属性可以根据不同的情况返回不同的值,可以用来实现类似 switch case 的功能。
<template>
<div>
<p v-if="result === 'A'">A</p>
<p v-if="result === 'B'">B</p>
<p v-if="result === 'C'">C</p>
</div>
</template>
<script>
export default {
data() {
return {
input: 'A',
}
},
computed: {
result() {
switch (this.input) {
case 'A':
return 'A'
case 'B':
return 'B'
case 'C':
return 'C'
default:
return ''
}
},
},
}
</script>
2. 使用 methods 方法
methods 方法可以根据不同的情况执行不同的方法,可以用来实现类似 switch case 的功能。
<template>
<div>
<button @click="handleClick('A')">A</button>
<button @click="handleClick('B')">B</button>
<button @click="handleClick('C')">C</button>
</div>
</template>
<script>
export default {
methods: {
handleClick(value) {
switch (value) {
case 'A':
this.methodA()
break
case 'B':
this.methodB()
break
case 'C':
this.methodC()
break
default:
break
}
},
methodA() {
console.log('method A')
},
methodB() {
console.log('method B')
},
methodC() {
console.log('method C')
},
},
}
</script>
原文地址: https://www.cveoy.top/t/topic/mke9 著作权归作者所有。请勿转载和采集!