【问题标题】:how to emit a value with a click event in vue.js如何在 vue.js 中通过单击事件发出值
【发布时间】:2018-11-15 10:52:25
【问题描述】:

我正在关注 Vuejs 文档并尝试通过点击事件发出一个值。

代码如下:

Vue 模板:

<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 实例:

    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
        }
    });

【问题讨论】:

    标签: vue.js vue-component


    【解决方案1】:

    检查Vue Custom Event,Vue 始终建议使用 kebab-case 作为事件名称。

    如上面Vue指南所说:

    与组件和道具不同,事件名称不提供任何自动 案例转换。相反,发出事件的名称必须 与用于侦听该事件的名称完全匹配。

    此外,DOM 模板中的 v-on 事件监听器将 自动转换为小写(由于 HTML 的 不区分大小写),因此 v-on:myEvent 将变为 v-on:myevent - 使 myEvent 无法收听

    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 () {
        return {
          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>

    【讨论】:

      猜你喜欢
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 2019-05-11
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 2018-10-21
      • 1970-01-01
      相关资源
      最近更新 更多