2017-08-24 109 views
1

我通过AJAX从Vue实例获取数据,并且需要将这些数据传递给组件。我现在正在学习Vue.js是如何工作的,但我发现文档有点零碎...如何将数据传递给Vue实例的嵌套组件

这里是aproximately我的代码:

<!DOCTYPE html> 
<html lang="en"> 
    <meta charset="UTF-8"> 
    <title>mysite</title> 
</head> 
<body> 

<div id="app"> 
    <parent-component></parent-component> 
</div> 

<template id="parent-component-template"> 
    <div id="the-template"> 
     <div class="the-list"> 
      <span is="sector-item" v-for="item in sectors" :sector="item"></span> 
     </div> 
     <button>Button</button> 
    </div> 
</template> 

<template id="sector-item-template"> 
    <span> 
     {{ sector.name }} 
    </span> 
</template> 

<!-- Vue.js --> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script> 

<script> 
    Vue.component('parent-component', { 
     template: '#parent-component-template' 
    }); 

    Vue.component('sector-item', { 
     props: ['sector'], 
     template: '#sector-item-template' 
    }); 

    let app = new Vue({ 
     el: '#app', 
     data: { 
      sectors: [{ 
       'id': 1, 
       'name': 'Industry' 
      }] 
     } 
    }); 
</script> 

</body> 
</html> 

我得到以下错误:

[Vue warn]: Property or method "sectors" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. 

我在哪里犯了一个错误?

+1

您需要将'sectors'作为道具传递给您的父组件 – thanksd

+0

https://vuejs.org/v2/guide/components.html#Props –

回答

1

我认为你的代码不完整。我试图模仿你想要什么,在片段波纹管:

Vue.component('parent-component', { 
 
    props: ['sectors'] 
 
}); 
 

 
Vue.component('child-component', { 
 
    props: ['item'] 
 
}); 
 

 
new Vue({ 
 
    el: '#app', 
 
    data: { 
 
    sectors: [ 
 
     { 
 
     'id': 1, 
 
     'name': 'Industry' 
 
     }, 
 
     { 
 
     'id': 2, 
 
     'name': 'Education' 
 
     } 
 
    ] 
 
    } 
 
});
.the-list > div { 
 
    padding: 5px; 
 
    border: 1px solid gray; 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script> 
 

 
<div id="app"> 
 
    <parent-component :sectors="sectors" inline-template> 
 
    
 
    <div class="the-list"> 
 
     <child-component :item="sector" :key="sector.id" v-for="sector in sectors" inline-template> 
 
     <div> 
 
      <span v-text="item.name"></span> 
 
      <button>Button</button> 
 
     </div> 
 
     </child-component> 
 
    </div> 
 
    
 
    </parent-component> 
 
</div>

的Vue的实例拥有的财产sectors和我通过这个属性为prop<parent-component>

现在<parent-component>有一个道具叫sectors接受的sectors从主Vue的实例值(也可能是另一个名字)。我已使用v-for遍历父组件道具的所有项目,将数组中的每个项目传递给<child-component>

<child-component>有一个名为item的道具,其中我传递了数组中每个元素的值。

您可以了解更多,here免费

我希望这个答案能够有所帮助。

+0

非常有帮助。非常感谢! :) – AntonioRomero

相关问题