2017-06-14 3 views
1

私は子供componentを持っていて、そのデータを親に渡したいと思っています。 私の子コンポーネントは次のようになります。私はemitのハンドラを置くべきですか?

// <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がグローバルに宣言された)bus.$onを配置するためのより良い場所を発見していないcreated()よりも、ドキュメントは、created()は、ページがロードされた後に初期化されるべきものであると述べています。 created()ブロックが動作します。 console.log(this.mycode)に入れてチェックしましたが、別の場所でハンドラを動かすべきですか?

  2. console.log(this.mycode);は何も印刷しないので、私のコードはmycode: ''を実行しないようです。

+0

あなたの子供はヴューの直接の子である場合は、バスのための必要はありません。 – Bert

答えて

1

私がコメントで述べたように、コンポーネントがあなたのVueの直接の子である場合、バスは必要ありません。

つまり、createdハンドラは、busイベントハンドラを追加しても問題ありません。

あなたの問題はthisです。ここでは一例であるHow to access the correct this inside a callback?

を参照してください

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

にあなたのハンドラを変更してみてください。

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

ありがとう、しかし私は子 'changeView();'からの呼び出しを変更できますか? –

+0

@ user1432751私はあなたを理解しているか分からない。あなたのイベントハンドラで 'changeView'メソッドを呼びたいのですか? – Bert

+0

はい、データを取得した後に 'changeView'を呼び出す必要があります。 "私たちはあなたのデータを持っています" –

関連する問題