0

I'm learning Vue Js and have created a simple button counter and in my methods object I created a click function to increment my counter variable. I added counter to data but it keeps telling me counter isn't defined in count().

<template>
   <div class="button-container">
      <button class="counter-button" v-on:click="count">Click Me</button>
      <p>Button has been clicked {{ counter }} times</p>
   </div>
</template>

<script>
   export default {
      name: 'AnotherComponent',
      data: function() {
         return {
            counter: 0
         }
      },
      methods: {
         count: function() {
            counter++;
         }
      }
   }
</script>

1 Answer 1

2

Your code is looking for a local variable called counter, but you never defined that.

Instead, you have to reference the instance property using this.counter:

 count: function() {
    this.counter++;
 }

See https://v2.vuejs.org/v2/guide/index.html#Handling-User-Input for a complete example.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.