2016-11-30 95 views
0

如何將由組件內的方法創建的對象數組傳遞給另一個組件?我嘗試過使用道具,但也許我對道具的工作原理是不正確的。在組件之間傳遞數據時遇到問題

<template> 
    <div class="media-body"> 

    <ul> 
     <li v-for="item in items" v-bind:class="{ active: item.active }">{{ item.text }} 
     </li> 
    </ul> 

     <button type="button" class="btn btn-danger" v-on:click="addItem">Test</button> 

</template> 

<script> 


export default { 

    data() { 
     return { 
      item: "a", 
      item2: "b", 
      item3: "c", 
      item4: "d", 
      items: [], 
    } 
     }, 

    methods: { 

     addItem: function() { 

      var testArray = this.item.concat(this.item2, this.item3, this.item4); 

      for (var i = 0; i < testArray.length; i++) { 
       this.items.push({ 
        text: testArray[i], 
        active: false }); 
      } 

      // if I check console.log(this.items) at this point I can see the data I want to pass 
     }, 

    } 
} 

</script> 

輔助組件我嘗試將數據傳遞給。

<template> 
    <div class="media-body"> 
     <div class="media-label">Title: 
     <textarea class="form-control" placeholder="Title"></textarea> 
     </div> 
     </div> 
</template> 

<script> 

export default { 

props: ['items'], 

data() { 
    return { 

    } 
}, 

</script> 

回答

1

傳給你必須寫在之後的第一個組件代碼的道具給其他組件:

  1. 在HTML代碼中添加<secondComponent :items="items" />
  2. 進口和VUE組件使用secondComponent這樣的:components: [secondComponent]

下面是這些變化的完整代碼:

<template> 
    <div class="media-body"> 
    <ul> 
     <li v-for="item in items" v-bind:class="{ active: item.active }">{{ item.text }} 
     </li> 
    </ul> 
     <button type="button" class="btn btn-danger" v-on:click="addItem">Test</button> 
    <secondComponent :items="items" /> 
    </template> 

<script> 
    import secondComponent from '/path/of/secondComponent' 
    export default { 
    components: [secondComponent] 
    data() { 
     return { 
      item: "a", 
      item2: "b", 
      item3: "c", 
      item4: "d", 
      items: [], 
    } 
     }, 

    methods: { 

     addItem: function() { 

      var testArray = this.item.concat(this.item2, this.item3, this.item4); 

      for (var i = 0; i < testArray.length; i++) { 
       this.items.push({ 
        text: testArray[i], 
        active: false }); 
      } 

      // if I check console.log(this.items) at this point I can see the data I want to pass 
     }, 

    } 
} 

</script> 

在第二組件已定義的項目,如道具,你可以以及在第二個組件的模板/ HTML中使用。

+0

如果我做的console.log(項目)我得到 「optimizerTitle.vue FAEE:36未捕獲的ReferenceError:項目沒有定義」 如果我做的console.log(this.items)我得到一個未定義錯誤。任何想法爲什麼? – Pyreal

相關問題