Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
-2
rated 0 times [  4] [ 6]  / answers: 1 / hits: 43182  / 7 Years ago, wed, april 5, 2017, 12:00:00

I have a very simple app:



<div id=show_vue>
<page-change page=bio @click=changeThePage></page-change>
<page-change page=health @click=changeThePage></page-change>
<page-change page=finance @click=changeThePage></page-change>
<page-change page=images @click=changeThePage></page-change>
</div>

Vue.component(page-change, {
template: <button class='btn btn-success'>Button</button>,
props: [page]
})

var clients = new Vue({
el: '#show_vue',
data: {
currentRoute: window.location.href
},
methods: {
changeThePage: function() {
console.log(this is working)
}
}
})


...but when I click the <page-change></page-change> button, nothing is logged to the console. I know I'm missing something simple but I'm not getting any errors.



How do I make my click fire changeThePage


More From » vue.js

 Answers
49

When you do :


<page-change page="bio" @click="changeThePage"></page-change>

That means that your are waiting page-change component emit the click event.


Best solution (thanks to @aeharding) : Use .native event modifier


<page-change page="bio" @click.native="changeThePage"></page-change>

Solution 1 : emit click event from child component :


Vue.component("page-change", {
template: "<button @click='clicked' class='btn btn-success'>Button</button>",
props: ["page"],
methods: {
clicked: function(event) {
this.$emit('click', this.page, event);
}
}
})

For information event is the default value passed by Vue for native event like click : DOM event


Solution 2 : emit directly from parent component :




Vue.component(page-change, {
template: <button class='btn btn-success'>Button {{ page }}</button>,
props: [page]
})

var clients = new Vue({
el: '#show_vue',
data: {
currentRoute: window.location.href,
pages: [
'bio', 'health',
'finance', 'images'
]
},
methods: {
changeThePage: function(page, index) {
console.log(this is working. Page:, page, '. Index:', index)
}
}
});

<script src=https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.5/vue.js></script>
<div id=show_vue>

<span v-for=(page, index) in pages :key=index+page
@click=changeThePage(page, index)>

<page-change :page=page></page-change>

</span>

</div>




[#58254] Monday, April 3, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leslijessalyng

Total Points: 650
Total Questions: 85
Total Answers: 109

Location: Croatia
Member since Mon, Sep 6, 2021
3 Years ago
leslijessalyng questions
Fri, Feb 21, 20, 00:00, 4 Years ago
Tue, Jul 30, 19, 00:00, 5 Years ago
Fri, Jul 5, 19, 00:00, 5 Years ago
Wed, Mar 13, 19, 00:00, 5 Years ago
;