Vue.js: simple click function doesn't fire

I have a very simple application:

<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 button <page-change></page-change>

, nothing is written to the console. I know I am missing something simple, but I am not getting any errors.

How to make my click changeThePage

+3


source to share


2 answers


When you do:

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

      

This means that your wait object is page-change

emitting an event click

.

Better solution (thanks @aeharding): use the .native event modifier

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

      

Solution 1: fire a click event from the 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 info event

- the default passed by Vue for a custom event of type click

: DOM event

Solution 2: emit directly from the 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>
      

Run codeHide result


+8


source


The best way to do this is by using an event modifier .native

.

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

+1


source







All Articles