我有一个 Orders
组件,它有一个子 OrdersTable
组件。我的 Orders
组件将一个名为 orders
的对象数组传递到我的 OrdersTable
组件。但是,当我尝试在子组件中使用 orders
时,它返回未定义。
这是我的Orders
组件片段:
<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>
这是我的 OrdersTable
组件片段:
<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>
我确定我已正确地将数据从父组件传递到子组件,所以我不太确定发生了什么...有人可以帮忙吗?
提前致谢!
最佳答案
您的代码(至少)有两个问题:
- 您正在尝试访问
data
函数中 undefined variableorders
。您可以尝试this.orders
但这也会失败,请参见 2 - 您正尝试在
created
Hook 中访问this.orders
,但您的数据是使用异步调用获取的,因此不能保证它会在中>创建
关于javascript - 父数据未在 vue.js 组件中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39359643/