页面A
<template>
<div class="hello">
<h1 @click="store">{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: 'myHello',
data () {
return {
msg: '点我传递',
selected:'',
showCondition:'',
}
},
methods:{
store(){
this.$router.push({path:'/myHello'})
}
},
destroyed(){
eventBus.$emit('test','我是新的');
},
beforeDestroy(){
// eventBus.$emit('test','我是新的');
}
}
</script>
页面A给页面B传值‘我是新的’,用eventBus,该eventBus注册在main.js里面,给下个页面传值的时候需要卸载destroyed或者beforeDestroy里面
window.eventBus = new Vue()
页面B
<template>
<div class="hello">
<h1 @click="getStore">{{ msg }}</h1>
<h2 @click="touterChange">{{testText}}{{num}}</h2>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: '点我接收',
selected:'',
showCondition:'',
testText:'旧的',
val:'',
num:1
}
},
methods:{
getStore(){
this.testText = this.val;
console.log(123);
this.num += 1
},
touterChange(){
this.$router.push({path:'/'})
}
},
created(){
var that = this;
eventBus.$on('test',function (val) {
that.testText = val
that.val = val;
console.log(val)
})
},
//在组件销毁的时候 注销掉监听的值
beforeDestroy() {
eventBus.$off('test')
},
}
</script>
页面B created生命钩子里面监听取值,如果用路由方式跳转的页面,必须在beforeDestroy周期里面关掉监听的这个值,以免造成返回页面来回过程中触发多次监听事件
eventBus.$on接收
(备注:如有不对的地方,欢迎大家指正)