2016-12-14 127 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 */ } 
} 

然后更改方法以返回问题列表而不是更改组件数据,然后完成。模板是正确的,你只是把逻辑放在稍微错误的地方。