必须调用异步 HTTP 请求的哪个 VueJS 生命周期钩子? [英] Which VueJS lifecycle hook must Asynchronous HTTP requests be called in?

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

问题描述

我想知道在呈现页面之前如何向我的服务器发送异步 GET 请求以检索数据并填充数据中的属性.我听说最好的方法是在 Vue js 提供的三个生命周期钩子之一中调用发送此请求的函数,这些钩子在 DOM 呈现之前运行.这三个是beforeCreate()created()beforeMount().理想情况下必须调用哪个请求?为什么?

解决方案

TL;DR 在一般(和安全)情况下,使用 created().

Vue 的初始化代码是同步执行的.

从技术上讲,您在 beforeCreate()created()beforeMount() 中运行的任何 ASYNChronous 代码只会在 之后响应所有这些钩子都完成了.看演示:

new Vue({el: '#app',之前创建(){setTimeout(() => { console.log('有史以来最快的异步代码') }, 0);console.log('beforeCreate hook done');},创建(){console.log('创建的钩子完成');},beforeMount() {console.log('beforeMount hook done');},安装(){console.log('挂载钩完成');}})

<script src="https://unpkg.com/vue/dist/vue.min.js"></脚本><div id="应用程序">检查控制台.

换句话说,如果你在 beforeCreate() 中进行 Ajax 调用,无论 API 响应有多快,响应只会在 created() 已被执行.


那么什么应该指导您的决定?

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?

解决方案

TL;DR in the general (and safe) case, use created().

Vue's initialization code is executed synchronously.

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>

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?

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆