知道vue組件同級(jí)傳值嗎?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>同級(jí)傳遞</title>
</head>
<body>
    <div id="app">
        <son1></son1>
        <son2></son2>
    </div>
</body>
<script src="./vue.js"></script>
<script>
    let nullVm=new Vue();
    var vm=new Vue({
        el:"#app",
        components:{
            "son1":{
                data(){
                    return {
                        mes:[1,2]
                    }
                },
                template:"<p @click='get'>send</p>",
                methods: {
                    get(){
                        nullVm.$emit("s1",this.mes)
                    }
                },
            },
            "son2":{
                template:"<p><p>",
                mounted(){
                    // let that=this;
                    nullVm.$on("s1",function (params) {
                        console.log(params)
                    })
                },
            }
        }
    })
    /*
一般同級(jí)傳遞都是指的是子組件與子組件之間的傳遞,因?yàn)楦赣H只有一個(gè),那就是Vue實(shí)例。
如果想把son1的數(shù)據(jù)傳給son2,
這里需要?jiǎng)?chuàng)建一個(gè)空實(shí)例Vue對(duì)象,然后利用事件方法$emit("自定義參數(shù)名","需要傳遞的數(shù)據(jù)"),
然后將空對(duì)象這個(gè)$emit(),整體寫(xiě)在函數(shù)內(nèi)。這樣他的數(shù)據(jù)就會(huì)傳出去了。誰(shuí)來(lái)接受呢?另一個(gè)同級(jí)組件需要用鉤子函數(shù)mounted,這個(gè)鉤子函數(shù)的意思是初始化頁(yè)面完成后,再對(duì)html的dom節(jié)點(diǎn)進(jìn)行一些需要的操作。
在mounted鉤子函數(shù)內(nèi),用空實(shí)例Vue對(duì)象調(diào)用$on("上一個(gè)組件的自定義參數(shù)名","回調(diào)函數(shù)")。
    */
</script>
</html>

作者:Vam的金豆之路

主要領(lǐng)域:前端開(kāi)發(fā)

我的微信:maomin9761

微信公眾號(hào):前端歷劫之路