1

Hey there i'm working on a simple game where if user click the button then the score will be plus i.e. 1.

new Vue({
  el: '#MyApp',
  data: {
    score: '10',
  },
  methods: {
    ScoreIncre: function(incre) {
      this.score += incre;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="MyApp">
  <p>My Score is {{score}</p>
  <button v-on:click="ScoreIncre(1)">Increase my Score</button>
</div>

Once button is clicked so instead of adding score by +1 it is displaying the output as 'My Score is 101'. What would be the possible cause of it? I have tried to parse the 'incre' to int but the result was same.

apple apple
  • 10,292
  • 2
  • 16
  • 36
Muhammad Khan
  • 85
  • 2
  • 17

4 Answers4

2

'10' is string. You need

data: {
    score: 10,
}
apple apple
  • 10,292
  • 2
  • 16
  • 36
1

Because score is '10' so it is a string not a number this is why when you increment '10'+1 it's '101' not 11 , you should change '10' by 10

1

'10' in your code is a string and not a number. That's why you can't increment it. Declare that as a number or without quotes like: 10

1

You need to keep 10 as number, not String, beside, you are missing a curly ending brace } in your template.

Check snippet:

new Vue({
  el: '#MyApp',
  data: {
    score: 10,
  },
  methods: {
    ScoreIncre: function(incre) {
      this.score += incre;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="MyApp">
  <p>My Score is {{score}}</p>
  <button v-on:click="ScoreIncre(1)">Increase my Score</button>
</div>
Towkir
  • 3,889
  • 2
  • 22
  • 41