Home > Mobile >  How con i change data value from a function?
How con i change data value from a function?

Time:12-08

I want to change count variable every click. If i put "count " in the on:clik event, it work. But, when i want to use a function doesn't do anythig. I also tried to put the component and the "new view" in the same file js, but doesn't work and show a blank page,why? thanks

Prova.js

Vue.component('prova', {
    data: function () {
        return {
            count: 0
        }
    },
    template: '<div><button v-on:click="Add">You clicked me {{ count }} times.</button></div>',
    methods:{
        Add: function(){
           prova.count  ;
        }
    }

});

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>prova component</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
    <script type="text/javascript" src="Prova.js"></script>

</head>
<body>
<section id="prova">
    <prova ></prova>

<script>
    new Vue({
        el: "#prova",
    })
</script>
</section>
</body>
</html>

CodePudding user response:

Actually I don't know what your second component is used to be, but you can solve your problem like this:

In the template

<template>
  <div>
    <button @click="addCount()"></button>
    <div>You have clicked the button {{count}} times.</div>
  </div>
</template>

• @click is the same like v-on:click

• you should write it like following: addCount()

In the script:

export default {
  data() {
    return {
      count: 0,
    }
  },

  methods: {
    addCount() {
      this.count  = 1;
    }
  }
}

• define count in your data

• use methods and on every click on your button add 1 to the current value

This should solve your problem. Please give me a short feedback if this worked out for you!

For little testing: You can also subtract from count. Just create a second button and make another click event an there you use this.count -= 1. This will subtract 1 each time you click it.

  • Related