Vue.js: Simple click function not firing

前端 未结 3 1599
不思量自难忘°
不思量自难忘° 2021-02-20 10:56

I have a very simple app:

相关标签:
3条回答
  • 2021-02-20 11:28

    apparently v-on:click seems to work better with the .native event modifier.

    try page="bio" v-on:click.native="changeThePage()"></page-change>. It worked for me.

    0 讨论(0)
  • 2021-02-20 11:44

    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>

    0 讨论(0)
  • 2021-02-20 11:44

    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

    0 讨论(0)
提交回复
热议问题