vue2: 无法通过 ajax 找到初始化组件数据的正确方法
vue2: can not find a proper way to initialize component data by ajax
我有一个组件,其数据由 ajax 初始化。我知道 vue.js 提供了几个生命周期钩子:Lifecycle-Diagram。但是对于 ajax 初始化数据,哪个钩子(beforeCreate、create、mounted 等)是最好的地方:
hook_name: function() {
ajaxCall(function(data) {
me.data = data;
});
}
目前,我在 mounted
中执行此操作,使其重新渲染组件。但我认为我们应该在第一次渲染之前获取数据。有人能想出最好的方法吗?
如果您想使用从 request
接收到的数据初始化您的组件,created()
将是最适合使用的钩子 但是 它是一个 request
,它 可能不会在 created
甚至 mounted()
结束时解决 (当你的 DOM 准备好显示内容!)。
因此请使用空数据初始化您的组件,例如:
data () {
return {
listOfItems: [],
someKindOfConfig: {},
orSomeSpecialValue: null
}
}
并在 created
挂钩中收到它们时分配实际值,因为这些空的 data
属性在那个时间点可用,例如:
created () {
someAPICall()
.then(data => {
this.listOfItems = data.listOfItems
})
/**
* Notice the use of arrow functions, without those [this] would
* not have the context of the component.
*/
}
您似乎没有使用(或不打算使用)vuex,但我强烈建议您使用它来管理商店中的数据。如果您使用 vuex
,您可以使用 actions
,它可以进行这些 api 调用,并且通过在您的组件中使用简单的 getters
,您可以访问 [=] 返回的值12=].
我有一个组件,其数据由 ajax 初始化。我知道 vue.js 提供了几个生命周期钩子:Lifecycle-Diagram。但是对于 ajax 初始化数据,哪个钩子(beforeCreate、create、mounted 等)是最好的地方:
hook_name: function() {
ajaxCall(function(data) {
me.data = data;
});
}
目前,我在 mounted
中执行此操作,使其重新渲染组件。但我认为我们应该在第一次渲染之前获取数据。有人能想出最好的方法吗?
如果您想使用从 request
接收到的数据初始化您的组件,created()
将是最适合使用的钩子 但是 它是一个 request
,它 可能不会在 created
甚至 mounted()
结束时解决 (当你的 DOM 准备好显示内容!)。
因此请使用空数据初始化您的组件,例如:
data () {
return {
listOfItems: [],
someKindOfConfig: {},
orSomeSpecialValue: null
}
}
并在 created
挂钩中收到它们时分配实际值,因为这些空的 data
属性在那个时间点可用,例如:
created () {
someAPICall()
.then(data => {
this.listOfItems = data.listOfItems
})
/**
* Notice the use of arrow functions, without those [this] would
* not have the context of the component.
*/
}
您似乎没有使用(或不打算使用)vuex,但我强烈建议您使用它来管理商店中的数据。如果您使用 vuex
,您可以使用 actions
,它可以进行这些 api 调用,并且通过在您的组件中使用简单的 getters
,您可以访问 [=] 返回的值12=].