vue 非父子元件傳值
阿新 • • 發佈:2019-02-17
頁面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接收
(備註:如有不對的地方,歡迎大家指正)