美文网首页
vue 组件(下篇)

vue 组件(下篇)

作者: 时光记忆forever | 来源:发表于2017-07-14 20:41 被阅读24次

自定义事件

父组件是使用 props 传递数据给子组件,但如果子组件要把数据传递回去,应该怎样做?那就是自定义事件!

使用 v-on 绑定自定义事件

每个 Vue 实例都实现了事件接口 (Events interface),即:

  • 使用 $on(eventName) 监听事件
  • 使用 $emit(eventName) 触发事件
<div id="counter-event-example">
    <p>{{ total }}</p>
    <button-counter v-on:increment="incrementTotal"></button-counter>
    <button-counter v-on:increment="incrementTotal"></button-counter>
</div>

<script>
    Vue.component('button-counter', {
        template: '<button v-on:click="increment22">{{ counter }}</button>',
        data: function () {
            return {
                counter: 0
            }
        },
        methods: {
            increment22: function () {
                this.counter += 1
                console.log("button-counter-------increment")
                this.$emit('increment')
            }
        },
    })
    new Vue({
        el: '#counter-event-example',
        data: {
            total: 0
        },
        methods: {
            incrementTotal: function () {
                console.log("example-------increment")
                this.total += 1
            }
        }
    })
</script>

运行结果:

相关文章

网友评论

      本文标题:vue 组件(下篇)

      本文链接:https://www.haomeiwen.com/subject/cavohxtx.html