0

I am using vue.js and try to recreate the "Listening to Events" example. They use the following code:

HTML

<div id="example-1">
  <button v-on:click="counter += 1">Add 1</button>
  <p>The button above has been clicked {{ counter }} times.</p>
</div>

JS

var example1 = new Vue({
  el: '#example-1',
    data: {
    counter: 0
  }
})

I want to do the same, but as its something I will do more often I want to create a component:

HTML

<div id="example-1">
  <counterButton></counterButton>
  <p>The button above has been clicked {{ counter }} times.</p>
</div>

JS

Vue.component('counterButton', {
  template: '<button v-on:click="counter += 1">Add 1</button>'
})

var example1 = new Vue({
  el: '#example-1',
    data: {
    counter: 0
  }
})

This does not seem to be working, while I receive the following warning:

[Vue warn]: Property or method "nextPage" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

As I am not used to javascript too much, I am simply not able to understand the error. I guess I have to somehow "link" the data value to my component?

1
  • This warning about something else, there is no nextPage property on your example. Commented Jun 22, 2017 at 6:40

1 Answer 1

3

Your component should be called like below.

<counter-button></counter-button>

This will fix the warning and the button will appear. However, your counter will not change (not the way you are expecting it at least).

Reason

This is because now a button is a standalone component and it does not know about the counter of the parent component.

I recommend to take a look at the official documentation of VueJs about the components and they have a nice example of a counter.

Side note:

If you wish to reuse one button at multiple components to increase only one counter you will have to implement events or use Vuex. These are, however, a bit advanced topics and you should cover the basics first.

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.