V-on: click in component doesn't work
The vue.js component creates a button that should call a function, but the function is never called, and v-on: the click is not shown when checking the chrome element. My html looks like this:
<bottomcontent></bottomcontent>
And my Vue looks 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
}
})
source to share
The problem is that I methods
have to use funcions and not objects.
methods: {
appendcontent: function() {
homepage.numberofdivs += 60
}
}
You should also adjust your markup accordingly.
var bottomcontent = {
template: '<div class="bottomcontent"> <div class="moreresults" v-on:click="appendcontent"> More Results </div></div>'
}
source to share
Some problems lead to crack.
In the appendcontent function, you must call the "this.homepage.numberofdivs" data.
and the correct demo is posted at https://jsfiddle.net/atsknydr/
methods : {
appendcontent: function() {
this.homepage.numberofdivs += 60;
console.log(this.homepage.numberofdivs);
}
}
source to share
First, as warns:
[Vue warn]: Do not mount Vue to <html> or <body> - mount to normal elements instead.
So, you have to create a type element <div id="app"></div>
to mount your application instead of <body>
.
The problem you are having is the scope problem. You are trying to call a method from within the scope of a component, so it doesn't find the method.
Have a look at the docs for a better understanding.
So, in order to make this work, you must change the method from the application area to the template area.
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>
source to share