本文介绍了必须在哪个VueJS生命周期挂钩中调用异步HTTP请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在渲染页面之前,我想向服务器发送异步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()
          • 为什么?
            • Use created()
            • Why?
              • State is only initialized between beforeCreate() and created(), so if you assign some data before created(), it would be lost.
              • 使用beforeMount()
              • 为什么?
                • Use beforeMount()
                • Why?
                  • I don't know anything that isn't available at created() and is available at beforeMount() other than the compiled this.$options.render render function (see source as well), so this case must really be a rare situation.

                  这篇关于必须在哪个VueJS生命周期挂钩中调用异步HTTP请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 23:40