Brian Patrick
Brian Patrick

Reputation: 341

Where/How do I define variables in data for Vue Js methods?

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>

Upvotes: 0

Views: 147

Answers (1)

str
str

Reputation: 45019

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.

Upvotes: 2

Related Questions