派发事件——$dispatch()

复制代码
复制代码
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
            <p>Messages: {{ messages | json }}</p>
            <child-component></child-component>
        </div>
        <template id="child-component">
            <input v-model="msg" />
            <button v-on:click="notify">Dispatch Event</button>
        </template>

    <script src="js/vue.js"></script>
    <script>
        // 注册子组件
        Vue.component('child-component', {
            template: '#child-component',
            data: function() {
                return {
                    msg: ''
                }
            },
            methods: {
                notify: function() {
                    if (this.msg.trim()) {
                        this.$dispatch('child-msg', this.msg)
                        this.msg = ''
                    }
                }
            }
        })
    
        // 初始化父组件
        new Vue({
            el: '#app',
            data: {
                messages: []
            },
            events: {
                'child-msg': function(msg) {
                    this.messages.push(msg)
                }
            }
        })
    </script>
    </body>
</html>
复制代码
复制代码

  1. 子组件的button元素绑定了click事件,该事件指向notify方法
  2. 子组件的notify方法在处理时,调用了$dispatch,将事件派发到父组件的child-msg事件,并给该该事件提供了一个msg参数
  3. 父组件的events选项中定义了child-msg事件,父组件接收到子组件的派发后,调用child-msg事件。
posted @ 2022-05-12 20:25  y世界第一  阅读(174)  评论(0)    收藏  举报