2016-09-02 2 views
0

전체 구성 인 하나의 구성 요소를 통해 '하위 구성 요소에'객체를 전달하려고 할 때 문제가 발생합니다. 기본적으로 <ul></ul> 템플릿과 <li></li> 템플릿이있는 간단한 예제를 만들었습니다.Vue가 하위 구성 요소에 데이터를 전달하는 중

나는 그것이 만들어 질 때까지 각각을위한 참조를 잃어 가고있는 것처럼 보인다. 문제가 발생하면 오류가 발생합니다.

vue.js:1023 [Vue warn]: Error when evaluating expression "model.id": 
    TypeError: Cannot read property 'id' of undefined (found in component: 
    <demo-list-item>) 

무엇이 잘못 되었나요?

나는 Vue에 대한 지식이 없기 때문에 근본적으로 생각합니다. 저는 정말 그것에 익숙하고 자신의 웹 사이트에서 학습하고 있습니다. 그래서 이것은 정말로 명백하고 어리석은 실수가 될 수 있습니다.

HTML :

<div id="app"> 
    <demo-list></demo-list> 
    <script id="demo-list-template" type="text/x-template"> 
     <ul> 
      <demo-list-item v-for="item in items"></demo-list-item> 
     </ul> 
    </script> 
    <script id="demo-list-item-template" type="text/x-template"> 
      <li data-id="{{model.id}}">{{ model.name }}</li> 
    </script> 
</div> 

자바 스크립트 :

// define 
var DemoList = Vue.extend({ 
    template: '#demo-list-template', 
    data : function(){ 
     return { 
      'items' : [ 
       { 
        'id' : 1, 
        'name' : 'this' 
       }, 
       { 
        'id' : 2, 
        'name' : 'that' 
       }, 
       { 
        'id' : 3, 
        'name' : 'something' 
       }, 
       { 
        'id' : 4, 
        'name' : 'nothing' 
       } 
      ] 
     } 
    } 
}); 

// List Item 
var DemoListItem = Vue.extend({ 
    template : '#demo-list-item-template' 
}); 

// register 
Vue.component('demo-list', DemoList); 
Vue.component('demo-list-item', DemoListItem); 

// create a root instance 
var Vue = new Vue({ 
    el: '#app', 
}); 

데모 : http://codepen.io/EightArmsHQ/pen/vXYWgz

답변

7

Component props doc에 따르면,이 같은 하위 구성 요소에 데이터를 전달할 수 있습니다

<child name="value"></child> 
당신이 항목의 배열을 통해 루프, 당신은 항목 객체를 가지고 템플릿에 따라서 동적 소품

, 대한

<child :name="value"></child> 

. 다만 당신의 아이 컴퍼넌트에 전달

<demo-list-item v-for="item in items" :item="item"> 

또한, 자녀의 구성 요소에, 당신은 당신이, item

var DemoListItem = Vue.extend({ 
    template : '#demo-list-item-template', 
    props: ['item'] 
}); 

당신은 소품을 확인할 수라는 소품을 얻기 위해 설정 기본값을 시도한다는 얘기를 해, 등

지금, 당신의 아이 템플릿에, 당신은 item 속성에 액세스 할 수 있습니다 (문서 참조)

<li data-id="{{item.id}}">{{ item.name }}</li> 
+0

이 모든 것이 수정되었으며 훌륭한 답변입니다. 감사합니다. Vue를 처음 사용했을 때 정말 이렇게 혼란 스럽습니다 ... "item in item": item = "item"'꽤 귀찮은 순간입니다! – Djave

+0

"item"항목 : itemtochild = "item"'으로 변경하여 더 명확하게 할 수 있습니다. – Quentin

관련 문제