P
P
PHVNTOW2022-01-03 18:33:26
Vue.js
PHVNTOW, 2022-01-03 18:33:26

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>


JS

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

1 answer(s)
W
Wispik, 2022-01-03
@Wispik

https://stackoverflow.com/questions/4923316/eval-...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question