问题描述
我想知道在渲染页面之前,我想向服务器发送异步GET请求以检索数据并填充数据中的属性.我听说做到这一点的最佳方法是调用Vue js提供的三个生命周期挂钩之一中发送此请求的函数,该挂钩在呈现DOM之前运行.这三个是beforeCreate()
,created()
,beforeMount()
.理想情况下必须调用哪个请求?为什么呢?
I'd like to know how before I render a page, I want to send an async GET request to my server to retrieve data and populate the properties in data. I heard the best way to do this is to call the function that sends this request in one of the three lifecycle hooks Vue js offers that operate before the DOM is rendered. The three are beforeCreate()
, created()
, beforeMount()
. Which one must this request be called in ideally? And why?
推荐答案
Vue的初始化代码是同步执行的.
Vue's initialization code is executed synchronously.
从技术上讲,您在beforeCreate()
,created()
,beforeMount()
中运行的所有ASYNChronous代码仅在完成这些钩子的 all 后才响应.观看演示:
Technically, any ASYNChronous code you run in beforeCreate()
, created()
, beforeMount()
will only respond after all of those hooks finish. See demo:
new Vue({
el: '#app',
beforeCreate() {
setTimeout(() => { console.log('fastest asynchronous code ever') }, 0);
console.log('beforeCreate hook done');
},
created() {
console.log('created hook done');
},
beforeMount() {
console.log('beforeMount hook done');
},
mounted() {
console.log('mounted hook done');
}
})
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<div id="app">
Check the console.
</div>
换句话说,如果您在beforeCreate()
中进行Ajax调用,则无论API响应速度如何,响应都只会在执行created()
之后的一段时间后处理.
In other words, if you make an Ajax call in beforeCreate()
, no matter how fast the API responds, the response will only be processed way later, way after the created()
has been executed.
那么,什么应该指导您的决定?
What should guide your decision, then?
- 是否需要尽快触发通话?
- 使用
beforeCreate()
- 为什么?
- 它比任何一个钩子都要运行早,但是...
- Need just to trigger a call as soon as possible?
- Use
beforeCreate()
- Why?
- It runs sooner than any of those hooks, but...
- 使用
created()
- 为什么?
- 状态仅在和
created()
,因此,如果您 在created()
之前分配一些数据,将会丢失 .
- Use
created()
- Why?
- State is only initialized between
beforeCreate()
andcreated()
, so if you assign some data beforecreated()
, it would be lost.
- 使用
beforeMount()
- 为什么?
- 我不知道
created()
上没有的任何东西,以及beforeMount()
上没有的任何东西. 除了已编译的this.$options.render
渲染函数 (请参见来源),因此这种情况确实很少见.
- Use
beforeMount()
- Why?
- I don't know anything that isn't available at
created()
and is available atbeforeMount()
other than the compiledthis.$options.render
render function (see source as well), so this case must really be a rare situation.
这篇关于必须在哪个VueJS生命周期挂钩中调用异步HTTP请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
- I don't know anything that isn't available at
- 我不知道
- State is only initialized between
- 状态仅在和
- Use
- 使用