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
With Vue, you can tie button clicks to functions you want to execute. The formal way to do this is to use the v-on:click attribute, however, Vue has a neat shortcut, @click .
To get a clicked element with Vue. js 2 first add a method in your component. Note the comment in the code below. Then simply pass document and $event via @click .
Simply use @click (v-on:click) to toggle Bool.
If you want to trigger click event without clicking a button manually, then you should use the click() method in Javascript. Example : click button on page load dynamically. For that we will create a button with an id my-btn . So that, we can select the button using the getElementById() method.
When you do :
<page-change page="bio" @click="changeThePage"></page-change>
That means that your are waiting page-change
component emit the click
event.
<page-change page="bio" @click.native="changeThePage"></page-change>
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
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>
The best way to do this is to use the .native
event modifier.
For example:
<my-custom-component @click.native="login()">
Login
</my-custom-component>
Source: https://vuejs.org/v2/guide/components.html#Binding-Native-Events-to-Components
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With