how to emit a value with a click event in vue.js

2019-05-16 12:35发布

I am very new in Vue JS. I am following Vuejs documentation and trying to emit a value with click event. Somehow I am making mistakes that's why it is not working.

So I am sorry if the question is some kind of obvious.

The code is something like this:

Vue Template:

<div id="app">
    <div class="container">
        <div class="col-lg-offset-4 col-lg-4">
            <sidebar v-on:incrementBtn="increment += $event"></sidebar>
            <p>{{ increment }}</p>
        </div>
    </div>
</div>

Vue instances:

    Vue.component('sidebar',{
        template:`
            <div>
                <button class="btn btn-info" v-on:click="$emit('incrementBtn', 1)">Increment on click</button>
            </div>
        `,
    });

    new Vue ({
        el:'#app',
        data:{
            increment:0
        }
    });

1条回答
做个烂人
2楼-- · 2019-05-16 13:29

Check Vue Custom Event, Vue always recommends using kebab-case for event names.

And as above Vue guide said:

Unlike components and props, event names don’t provide any automatic case transformation. Instead, the name of an emitted event must exactly match the name used to listen to that event.

And

Additionally, v-on event listeners inside DOM templates will be automatically transformed to lowercase (due to HTML’s case-insensitivity), so v-on:myEvent would become v-on:myevent – making myEvent impossible to listen to.

Vue.component('sidebar',{
    template:`
        <div>
            <button class="btn btn-info" v-on:click="$emit('increment-btn', 1)">Increment on click</button>
        </div>
    `
})

new Vue ({
  el:'#app',
  data:{
      increment:0
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
    <div class="container">
        <div class="col-lg-offset-4 col-lg-4">
            <sidebar v-on:increment-btn="increment += $event"></sidebar>
            <p>{{ increment }}</p>
        </div>
    </div>
</div>

查看更多
登录 后发表回答