Trung Tran
Trung Tran

Reputation: 13721

Parent data not defined in vue.js component

I have an Orders component that has a child OrdersTable component. My Orders component passes an array of object called orders to my OrdersTable component. However, when I try to use orders in the child component, it returns undefined.

Here is my Orders component snippet:

<template>
    <div class="container">
        <h1>My Orders</h1>
        <orders-table :orders="orders" :token="token"></orders-table>
    </div>
</template>


<script>

import OrdersTable from './OrdersTable.vue'

module.exports = {

    components: {

        OrdersTable

    },

    data: function () {
        return {
            orders: '',
            token: localStorage.getItem('jwt')
        }
    },

    created: function () {

        this.getAllOrders()

    },

    methods: {

        getAllOrders: function () {

            var token = localStorage.getItem('jwt')
            var self = this

            $.ajax({
                type: 'GET',
                url: 'http://localhost:3000/api/orders',
                data: {token: localStorage.getItem('jwt')},
                success: function (data) {
                    self.orders = data
                },
                error: function (a, b, c) {
                    console.log(a)
                    console.log(b)
                    console.log(c)
                }
            })


        },

    },

}

</script>

Here is my OrdersTable component snippet:

<template>
    <div class="container"> 
        <v-client-table :data="orders" :columns="columns" :options="options"></v-client-table>
    </div>
</template>


<script>


module.exports = {

  data: function () {
    return {
        columns:['order_id', 'po_num','order_date', 'order_total'],
        tableData: orders, //returns undefined
        options: {
          dateColumns: ['order_date'],
          headings: {},
        },

    }

  },

  created: function () {
    console.log('orders:')
    console.log(this.orders) //returns undefined
  }

  props: ['orders']

}

</script>

I'm sure I passed data from the parent to child component correctly so I'm not really sure what's going on... Can someone help?

Thanks in advance!

Upvotes: 1

Views: 3362

Answers (1)

pkawiak
pkawiak

Reputation: 1329

There are (at least) two problems with your code:

  1. You are trying to access undefined variable orders in your data function. You could try this.orders but this would also fail, see 2
  2. You are trying to access this.orders in created hook, but your data is fetched using async call, so there's no guarantee that it will be there in created

Upvotes: 2

Related Questions