4
votes

A vue.js component creates a button which should call a function, but the function is never called and the v-on:click is not visible in Chrome's element inspect. My html goes like this:

<bottomcontent></bottomcontent>

And my Vue is like this:

var bottomcontent = {
  template: '<div class="bottomcontent"><div class="moreresults" v-on:click="appendcontent">More Results</div></div>'
}
new Vue({
  el : 'body',
  data : {
    homepage:{
      numberofdivs: 60
    }
  },
  methods : {
      appendcontent: function() {
        homepage.numberofdivs += 60
    }
  },
  components: {
    'bottomcontent': bottomcontent
  }
})
3

3 Answers

0
votes

The problem is that methods has to use funcions, not objects.

methods: {
  appendcontent: function() {
    homepage.numberofdivs += 60
  }
}

You also have to correct your markup accordingly.

var bottomcontent = {
  template: '<div class="bottomcontent"> <div class="moreresults" v-on:click="appendcontent"> More Results </div></div>'
}
0
votes

There are some problems lead to the crack.

In the function appendcontent,you should call the data "this.homepage.numberofdivs".

and the correct demo is posted on https://jsfiddle.net/atsknydr/

methods : {
  appendcontent: function() {
    this.homepage.numberofdivs += 60;
    console.log(this.homepage.numberofdivs);
}

}

0
votes

First, as the warning says:

[Vue warn]: Do not mount Vue to <html> or <body> - mount to normal elements instead.

So, you should create an element like <div id="app"></div> to mount your app instead of <body>.

The problem you are facing is a scope problem. You are trying to call a method from the inside a component scope, that is why it's not finding the method.

Take a look at the docs to understand better.

So, in order to make this work you should change the method from the app scope to the template scope.

Your html:

<body>
    <div id="app">
        <bottomcontent></bottomcontent>
    </div>
</body>

Your js:

<script>
var bottomcontent = {
    template: '<div class="bottomcontent"><div class="moreresults" v-on:click="appendcontent">More Results</div></div>',
    data: function () {
        return {
            homepage: {
                numberofdivs: 60
            }
        }
    },
    methods: {
        appendcontent: function () {
            console.log('Called method!');
            this.homepage.numberofdivs += 60
        }
    }
}

new Vue({
    el: '#app',
    components: {
        'bottomcontent': bottomcontent
    }
})
</script>