Answer the question
In order to leave comments, you need to log in
How to solve the problem with eval?
I'm making a calculator on Vue (api) and ran into a problem.
Everything seems to be working fine, but when you enter a non-logical equation into the input, for example: " + -+ * + " eval gives an error, which is logical, but how can I get around it or solve it?
I tried to deal with Errors, but I didn’t quite understand it.
HTML
<div id="app">
<h1>Vue Calculator</h1>
<main class="main">
<input v-model="input" />
<div @click="clear" class="num">C</div>
<div @click="result" class="num">=</div>
<div @click="num('/')" class="num">/</div>
<div @click="num('*')" class="num">*</div>
<div @click="num('+')" class="num">+</div>
<div @click="num('-')" class="num">-</div>
<div @click="num(9)" class="num">9</div>
<div @click="num(8)" class="num">8</div>
<div @click="num(7)" class="num">7</div>
<div @click="num(6)" class="num">6</div>
<div @click="num(5)" class="num">5</div>
<div @click="num(4)" class="num">4</div>
<div @click="num(3)" class="num">3</div>
<div @click="num(2)" class="num">2</div>
<div @click="num(1)" class="num">1</div>
</main>
</div>
const app = Vue.createApp({
data() {
return {
input: "",
}
},
methods: {
num(n) {
this.input += "" + n
},
clear() {
this.input = ""
},
result() {
if(this.input === "") {
return
} else {
this.input = eval(this.input)
}
},
},
})
app.mount("#app")
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question