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

大兔子大兔子 提交于 2019-12-07 02:33:32

问题


I am following Vuejs documentation and trying to emit a value with click event.

The code follows:

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:


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>


来源:https://stackoverflow.com/questions/50708772/how-to-emit-a-value-with-a-click-event-in-vue-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!