为什么在 computed 里面定义异步数据属性?
来源:4-3 tab 组件抽象和封装

qq_缺南摸了个北_0
2019-01-03
我发现,一开始按照自己的思路。
_getSellers () {
getSeller()
.then(seller => {
this.seller = seller
})
},
_getGoods () {
getGoods().then(goods => {
this.goods = goods
})
},
_getRatings () {
getRatings().then(ratings => {
this.ratings = ratings
})
}
data () {
return {
seller: {},
goods: {},
ratings: {},
tabs () {
return [{
label: '商家',
component: Seller,
data: {
seller: this.seller // data是个静态的玩意,直接传递了,就是{}.异步数据还没有回来,但是回来了,数据变化了,为什么子视图不能检测到这个变换,拿到数据呢?
}
},
{
label: '商品',
component: Goods,
data: this.goods
}, {
label: '评价',
component: Ratings,
data: this.ratings
}]
}
},
发现在子组件里拿不到异步数据,是{}
对象。
但是如果把data
丢在 computed
里就可以拿到了。
原因是因为:
- axios请求数据是异步的,可能所有组件都加载好了,数据还没有回来,所以是
data
里定义的{}
- 把数据定义在
computed
里,由于computed
会检测属性data.set
,所以,当异步数据回来了之后,computed
才会执行。所以其实在传递<tab :tabs="tabs"></tab>
的实际是非常靠后的。
问题是:
当给一个子组件传递 data
定义的数据,一开始这个 data
定义的数据是空对象{}
. 但是等待接口数据回来的{data}
,数据改变了。但是,data
不是单项数据流的吗?
一开始数据没回来,是 {}
可以理解,为什么数据回来了之后,子组件依赖的那个 props
就不能接受到新的数据了吗?
写回答
2回答
-
ustbhuangyi
2019-01-03
数据回来了,seller 发生了变化,所以 tabs 会重新计算,求得新值,然后作为 props 传入子组件,子组件 props 变化重新渲染。
00 -
qq_缺南摸了个北_0
提问者
2019-01-03
在仅仅使用 `data` 的情况下,我使用子组件的 `updated` 钩子,也拿不到从父组件异步回来的数据。
00
相似问题