簡體   English   中英

Vue 3 Props 在正確綁定后無法處理子組件。 它在子組件中返回未定義

[英]Vue 3 Props is not working on child components after binding it correctly. It returns undefined in child component

我是 Vue 和 Laravel 的新手。 這是我的父元素,我正在從運行良好的數據庫中獲取項目。 然后將其綁定到子組件。

<template>
  <div class="todoListContainer">
    <div class="heading">
      <h2 id="title">Todo List</h2>
      <AddItemForm></AddItemForm>
    </div>
    <ListView 
    v-bind:items="items"/>
  </div>
</template>

<script>

import AddItemForm from "./AddItemForm.vue"
import ListView from "./ListView.vue"

export default {
  components: {
    AddItemForm,
    ListView
  },
  mounted() {
    this.getList()
    console.log(this)
  },
  data() {
    return {
      items: [], // Stored all the items in an array and i binded it on ListView Component
    }
  },
  methods: {
    getList: function  () {
      axios.get('api/items')
      .then(response => {
        this.items = response.data
        console.log( this.items )
      })

      console.log( this.items )
    }
  }
}
</script>

在我的子組件中,當我嘗試控制台記錄道具時,它返回未定義。 下面是我的 ListView 子組件。

<template>
  <div>
    <div 
    v-for="{item, index} in items" :key="index">
      <ListItem 
      v-bind:item="item" class="item"/>
    </div>
  </div>
</template>

<script>
  import ListItem from './ListItem.vue'
export default {
  // Props not working
  // On line 4 i looped through the items and then bind it to ListItem component
  props: [ 'items' ],
  components: {
    ListItem
  },
  created() {
    console.log( this.items )
  }

}
</script>

我已經按照書本做了一切。 創建一個收集所有數據並將其綁定到子組件的方法。

有人可以幫我嗎?

子組件是在收到 api 調用之前創建的,因此在 created 鈎子中還沒有。 快速修復是添加 v-if 以便在項目准備好后呈現子組件:

   <ListView v-if="items.length > 0" v-bind:items="items"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM