鍍金池/ 問(wèn)答/HTML/ vue中 emit實(shí)現(xiàn)原理是什么

vue中 emit實(shí)現(xiàn)原理是什么

看到vue子組件像父組件傳遞數(shù)據(jù)的方式是:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript" src="vue.js"></script>
</head>
<body>
    <!-- 子組件向父組件傳遞數(shù)據(jù) -->
    <div id="box">
        <v-parent></v-parent>
    </div>

    <!-- 父組件模板 -->
    <template id="parent">
        <div>
            <span>{{msgParent}}</span>
            <v-child @child-info="get"></v-child>
        </div>
    </template>

    <!-- 子組件模板 -->
    <template id="child">
        <div>
            <button @click="send">send</button>
            <!-- <p>{{msgChild}}</p> -->
        </div>
    </template>
    <script type="text/javascript">
        var app = new Vue({
            el:'#box',
            components:{
                // 父組件
                'v-parent':{    
                    data() {
                        return {
                            msgParent:'hello'
                        }
                    },
                    template:'#parent',
                    methods:{
                        get(msg){
                            this.msgParent = msg 
                        }
                    },
                    // 子組件
                    components:{
                        'v-child':{            
                            data(){
                                return {
                                    msgChild:'child'
                                }
                            },
                            template:'#child',
                            methods:{
                                send(){
                                    this.$emit('child-info',this.msgChild)
                                }
                            }
                        }
                    }
                }
            }
        })
    </script>
    
</body>
</html>

看起來(lái)就是子組件設(shè)置點(diǎn)擊事件,然后傳值 父組件用參數(shù)接收
那這個(gè)實(shí)現(xiàn)原理是什么 是不是說(shuō)必須要點(diǎn)擊子組件才能進(jìn)行數(shù)據(jù)傳遞?

回答
編輯回答
編輯回答
維他命

因?yàn)樽咏M件進(jìn)行傳值其父組件應(yīng)該有一個(gè)觸發(fā)條件
而去知道何時(shí)觸發(fā)可以進(jìn)行監(jiān)聽(tīng)在這里你可以使用點(diǎn)擊事件也可以是其他的事件
子組件向父組件傳遞值如果需要父組件去進(jìn)行顯示 那么這個(gè)顯示條件或者說(shuō)值得獲取一定要有觸發(fā)的
而原理呢就是事件監(jiān)聽(tīng)
也可以說(shuō)是發(fā)布訂閱模式

2017年5月21日 20:29
編輯回答
短嘆

源碼中可以看到,emit 其實(shí)就是從改組件中綁定的事件events 找到對(duì)應(yīng)的事件上所有的方法,然后遍歷執(zhí)行,你應(yīng)該去看看vue源碼中事件機(jī)制就知道了

2017年5月3日 16:13
編輯回答
萌小萌

點(diǎn)擊只是觸發(fā)的時(shí)機(jī),你也可以不通過(guò)點(diǎn)擊觸發(fā)這個(gè),emit只是一個(gè)普通的函數(shù),你想什么時(shí)候觸發(fā)都行

2017年10月25日 18:20
編輯回答
初念

理解下 觀察者模式

2018年3月17日 06:34