2017-06-14 77 views
1

我有孩子component並想將一些數據傳遞給它的父項。 我的子組件的樣子:我應該在哪裏放置處理程序?

// <button @click="sendClick($event)">Send</button> 
// ... 
data: function(){ 
    return { 
      mycode: "" 
     } 
    }, 
    methods: { 
     sendClick(e) 
     { 
      bus.$emit('change', this.mycode); 
     } 
} 

我父組件的樣子:

var app = new Vue({ 
    el: '#app', 
    data: { 
    currentView: 'past-form', 
    mycode: '' 
    }, 
    methods: 
    { 
    changeView() 
    { 
     this.currentView = 'past-form' 
     console.log(this.mycode); 
    }, 

    }, 

    created() 
    { 
     bus.$on('change', function(mycode){ 
      this.mycode = mycode; 

     }); 
    } 

}) 
  1. 我還沒有找到一個更好的地方放置bus.$onbus全局聲明)比created(),但是文檔聲明created()適用於在頁面加載後應該初始化的內容。 created()塊的工作;我檢查了它console.log(this.mycode),但我應該移動發射處理程序在其他地方?

  2. 這看起來像我的代碼不執行mycode: '',因爲console.log(this.mycode);不會打印任何東西。

+0

如果你的孩子是Vue公司的直接孩子,沒有必要一輛公交車。 – Bert

回答

1

正如我在評論中提到的,如果你的組件是你的Vue的直接子,那麼就不需要總線了。

也就是說,created處理程序適用於添加您的bus事件處理程序。

我希望您遇到的問題是this問題。試着改變你的處理程序

bus.$on('change', mycode => this.mycode = mycode) 

How to access the correct this inside a callback?

下面是一個例子。

console.clear() 
 

 
const bus = new Vue() 
 

 
Vue.component("child", { 
 
    template: `<button @click="sendClick($event)">Send</button>`, 
 
    data: function() { 
 
    return { 
 
     mycode: "something" 
 
    } 
 
    }, 
 
    methods: { 
 
    sendClick(e) { 
 
     bus.$emit('change', this.mycode); 
 
    } 
 
    } 
 
}) 
 

 
var app = new Vue({ 
 
    el: '#app', 
 
    data: { 
 
    currentView: 'past-form', 
 
    mycode: '' 
 
    }, 
 
    methods: { 
 
    changeView() { 
 
     this.currentView = 'past-form' 
 
     console.log(this.mycode); 
 
    }, 
 

 
    }, 
 

 
    created() { 
 
    bus.$on('change', mycode => { 
 
     this.mycode = mycode 
 
     this.changeView() 
 
    }) 
 
    } 
 
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script> 
 
<div id="app"> 
 
    <child></child> 
 
    Parent mycode: {{mycode}} 
 
</div>

+0

謝謝,但我怎麼可以改變來自child'changeView();'的調用? –

+0

@ user1432751我不知道我理解你。你想在你的事件處理程序中調用'changeView'方法嗎? – Bert

+0

是的,我需要在獲取數據後調用'changeView'。並顯示到用戶頁面「我們得到了您的數據」 –

相關問題