Can someone assist me with my Vue.js calculator issue? I am facing a problem where the output gets added to the expression after using try and catch. How can I ensure that both ERR and the output are displayed in the {{output}} section? Any help would be appreciated!
https://i.sstatic.net/7dORR.png
https://i.sstatic.net/BcrnG.png
Here is the specific part causing trouble:
else if (but == "=") {
try {
eval(this.expression)
// this.output = eval(this.expression)
} catch (error) {
this.output = "ERR"
// throw e;
}
}
For reference, here is the full code:
<html>
<head>
<title>calculator</title>
<!-- Vue 3: development -->
<script src="https://unpkg.com/vue@next"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css"
integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ"
crossorigin="anonymous">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
<meta charset="UTF-8">
</head>
<body>
<div id="app" class="container" style="width: 400px;">
<div class="row border m-3 text-right" style='height:100px;'>
<div class="col">
{{expression}}
{{output}}
</div>
</div>
<div class="row text-center">
<div class="col">
<template v-for="i in button.length">
<button id="button[i-1]"class="btn btn-light m-2" style="width:50px" @click="action(button[i-1])">
{{button[i-1]}}
</button>
<br v-if=" i % 4 == 0">
</template>
</div>
</div>
</div>
</div>
</body>
<script>
Vue.createApp({
data() {
return {
expression: "",
output: "",
button: ["1","2","3","AC", "4", "5", "6", "+", "7", "8", "9", "-", "0", ".", "="]
};
},
methods: {
action(but) {
console.log(but)
if (this.expression == "" && (but == "+" || but =="-")){
this.expression = "0" + but
}
else if (but == "=") {
try {
eval(this.expression)
// this.output = eval(this.expression)
} catch (error) {
this.output = "ERR"
// throw e;
}
}
else{
this.expression = this.expression + but
}
// if =
if (but == "AC") {
this.expression = ""
this.output = ""
}
}
},
computed: {
}
}).mount('#app')
</script>
</body>
</html>