鍍金池/ 問(wèn)答/HTML/ 在vue的cli腳手架中同級(jí)頁(yè)面bus傳遞參數(shù),為啥數(shù)據(jù)不會(huì)更新....

在vue的cli腳手架中同級(jí)頁(yè)面bus傳遞參數(shù),為啥數(shù)據(jù)不會(huì)更新....

跳轉(zhuǎn)前的頁(yè)面代碼

<template>
    <div>
        <button @click="sendMsg">send</button>
    </div>
</template>

<script>
export default {
    name:"demo",
    data: function () {
        return {
            content: "Yin Han"
        } 
    },
    methods: {
        sendMsg: function(){
            this.bus.$emit('msg',"sssss")
            this.$router.push('/Demo1')
        }
    }
}
</script>

跳轉(zhuǎn)后的頁(yè)面代碼

<template>
    <div>
        <button>{{getMsg}}</button>
        <button @click="back">back</button>
    </div>
</template>

<script>
export default {
    name: "demo1",
    data: function(){
        return {
            getMsg: "123"
        }
    },
    methods: {
        back: function(){
            this.$router.push('/')
        }
    },
    mounted: function(){
        this.bus.$on('msg',function(msg){
            this.getMsg = msg;
            this.bus.$off('msg')
        })
    }
}
</script>

所想的應(yīng)該在A頁(yè)面點(diǎn)擊send之后會(huì)跳轉(zhuǎn)B然后B通過(guò)BUS拿到值更新了getMsg,但是實(shí)際操作過(guò)程并沒(méi)有,并且,在第一次點(diǎn)send時(shí)候$on沒(méi)有觸發(fā),第二次之后才會(huì)觸發(fā),參考了Vue中同級(jí)組件使用bus傳值如何優(yōu)雅地完成?但是并沒(méi)有給到有效的解決。

回答
編輯回答
誮惜顏

監(jiān)聽在前,觸發(fā)在后;然而你卻正好相反

2017年12月15日 17:48
編輯回答
別傷我

第一次:前者觸發(fā)的時(shí)候,后者的生命周期都還沒(méi)開始,emit的事件沒(méi)有被接收。
第二次:后者的生命周期已經(jīng)開始了,在mounted中注冊(cè)了事件監(jiān)聽,且還沒(méi)有被emit,這個(gè)監(jiān)聽未銷毀。然后前者再一次emit的時(shí)候,這個(gè)監(jiān)聽就起了作用,所以才會(huì)覺得是第二次后才觸發(fā)。

2017年3月23日 10:17
編輯回答
尛曖昧

這就像你在晚上說(shuō)今天早上我要干什么,而早上的你并不知道要干這件事。

2017年4月25日 20:49