2017-01-16 15 views
1

私はVueで遊び始めましたが、propsを使ってデータをコンポーネントに渡そうとすると問題が発生しました。 (Hello.vue中)this.myData以下のコードでは、いくつかの理由でundefinedあるVuejs - 小道具を持つ親から子にデータを渡す

App.vue

<script> 
import Hello from './components/Hello' 

export default { 
    name: 'app', 
    data() { 
    return { 
     myData: 'this is my data' 
    } 
    }, 
    components: { 
    Hello 
    } ... 
</script> 

Hello.vueあなたは親のように子コンポーネントを使用する必要が

<script> 
export default { 
    name: 'hello', 
    props: ['myData'], 
    data() { 
    return { 
     msg: 'Welcome to Your Vue.js App' 
    } 
    } 
    mounted: function() { 
     console.log(this.myData) 
    } 
} ... 
</script> 

答えて

5

、そう:

// inside app.vue 
<template> 
    <hello :myData='myData'></hello> // I believe this is your objective 
</template> //:myData is binding the property from the components data field, without using it, you will get myData as `string` in the child component. 

<script> 
    export default { 
    name: 'app', 
    data() { 
    return { 
     myData: 'this is my data' 
    } 
    }, 
    components: { 
    Hello 
    } 
</script> 

OPはpへの方法を要求しました子どもをテンプレートにすることなく小道具を子供にぶち当てる。

だから私ははいこの方法が動作しているdocumentation

Vue.component('hello', { 
    render: function (createElement) { 
    return createElement(
     <tag-names> 
    ) 
    }, 
    props: { 
    myData: parentComponent.myData // you need to give the parent components' data here. 
    } 
}) 
+1

へのリンクを掲載しています。したがって、データは常にテンプレートを通過する必要がありますか?もし私がちょうど実際にそれをレンダリングせずにデータを渡したいのであれば(例えば、いくつかの設定のような)? –

+1

あなたのケースでは、 'eventBus'やvuexストアを使うようなテンプレートのレンダリングが不要なコンポーネント間のデータ交換を実現する方法があります。小道具は最善の方法で、子をレンダリングする必要がありますテンプレート内のコンポーネント。方法はありますが、私の答えはそれで更新されますが、レンダリング機能が呼び出されます。それは大丈夫だと思われますか? –

+0

ありがとう!私は小道具を使って気にしない。それを行う正しい方法と思われます。データはテンプレートを介して送信されるということは理解できません。 –

関連する問題