I
I
Igor2021-02-17 10:56:25
Vue.js
Igor, 2021-02-17 10:56:25

How to make it so that when the checkbox is toggled, it adds some value to the variable?

Just the way I'm trying to do it like the example below doesn't work

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<div id="app">
    <input type="number" v-model.number="test1">
    <input type="number" v-model.number="test2">
    <input type="checkbox" v-model="addCheckbox" v-on:change="add()"> +
    
    <button v-on:click="calc() , add()">Ok</button>
    <span>total:{{total}}</span>

</div>
    


<script src="https://unpkg.com/[email protected]"></script>
<script src="main.js"></script>
</body>
</html>

Vue.createApp({
    data(){
        return{
            test1: '',
            test2: '',
            total:'',
            all:'',
            addCheckbox: true,
        }
    },
    methods:{
        calc(){
           
            this.all = this.test1 * this.test2;
                       
        },
        add(){
            switch (this.addCheckbox) {
                case true:
                    
                    this.total = this.all + 1000;

                    break;
            
                case false:

                    this.total = this.all - 1000;

                    break;
            }
        }
        
    }


        
}).mount('#app');

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-02-17
@invex

Make total a computed property:

computed: {
  total() {
    return this.value1 * this.value2 + this.checkbox * 1000;
  },
},

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question