2016-12-14 108 views
0

我正在使用Laraval Spark,並且在組件中有一個組件。在子組件中使用父組件數據Vue Js

<parent-component :user="user"> 

    <child-component :user="user" :questions="questions"></child-component> 

<parent-component> 

在我父組件我有我的數據的方法問題的數據:

props: ['user'], 
data(){ 
    return { 
     questions: { 
      // these are set in another method in this file 
     }, 
    } 
}, 

正如你所看到的,我已經加入:問題到我的子組件,希望的是能夠使用因爲我需要循環它們,因此該組件中存在問題。

在爲孩子組件我的js文件我有:

props: ['user', 'questions'], 

但是,試圖利用問題,當我不像它包含了所有的信息的用戶默認對象。

如何來正確地完成作爲即時通訊只是猜測目前...

下面是子組件的js文件:

Vue.component('control-question-navigation', { 
    props: ['user', 'questions'], 
    data() { 
     return { 
     // 
     } 
    }, 
    methods: { 
    }, 
    mounted() { 
     var $this = this; 
     console.log($this.questions); // return standard object 
     console.log($this.user); // returns the user data correctly 
    } 
}); 
+0

你可以顯示你的「孩子組件」,你如何看待問題? – Saurabh

+0

@saurabh更新了問題以顯示js文件。我可以在我的內聯模板中訪問問題數據,但不能在我的js中訪問。 – Lovelock

回答

0

我覺得這是編譯的問題模板範圍。

您似乎正在使用稱爲Content Distribution with Slots的東西,但對模板變量的範圍確定不正確。

編號:

經驗的成分範圍一個簡單的規則是:從頁面https://vuejs.org/v2/guide/components.html#Compilation-Scope

報價

父模板中一切都在父範圍編制;子模板中的所有內容都在子範圍內編譯。

我假設模板下面幾行屬於你的根組件:

<div id="app"> 
    <parent-component :user="user"> 
     <child-component :user="user" :questions="questions"></child-component> 
    <parent-component> 
</div> 

在這裏,用戶已經在根組件,因此它是提供給兩個parent-componentchild-component。但是您的questionsparent-component中定義,而不在root中定義。

根據上面鏈接中的編譯範圍文檔,您應該在根組件中還有questions以及user。否則,您應該將您的父組件模板移動到它自己的vue文件或父組件定義的模板字符串中。

編輯:爲清楚起見,可能的解決方案

選項1:你可以定義你的根組件,以及包括questions也把它連同user

new Vue({ 
    el: '#app', 
    data: { 
     user: "test user", 
     questions: ["one", "two", "three"] 
    } 
}); 

上述根組件將使userquestions都可用於parent-componentchild-component

選項2:你能避免使用內容分發與插槽,而是使用一個模板字符串:

Vue.component("parent-component", { 
    template: ` 
     <child-component :user="user" :questions="questions"></child-component> 
    `, 
    props: ["user"], 
    data: function() { 
     return { 
      questions: {} // You can initialize this in a local method here 
     } 
    } 
    // ... 
}) 

現在你child-component就能得到this.questions屬於你的parent-component

+0

優秀的迴應是有道理的。我有一個閱讀周圍,並考慮實現這一目標的另一種方法。 – Lovelock

+0

我用兩個選項擴展了我的答案以解決此問題。假設這是問題,它可以很容易地修復。 – Mani

+0

謝謝,我來看看,讓你知道。 – Lovelock

0
questions: { 
     // these are set in another method in this file 
    } 

您想使用計算屬性。

computed: { 
    questions(){ return this.anotherMethodInThisFile() } 
}, 
methods: { 
    anotherMethodInThisFile(){ return /* many questions */ } 
} 

然後更改方法以返回問題列表而不是更改組件數據,然後完成。模板是正確的,你只是把邏輯放在稍微錯誤的地方。