本文介绍了Vue.js中创建和挂载事件之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Vue.js文档描述了创建的已挂载的事件,如下所示:

Vue.js documentation describes the created and mounted events as follows:

created





mounted



在服务器端渲染期间不会调用此挂钩。

This hook is not called during server-side rendering.

我理解这个理论,但我有 2个问题关于练习:

I understand the theory, but I have 2 questions regarding practice:


  1. 是否会使用创建的 已挂载

  2. 我可以在实际中使用创建的事件 - 生活(真实代码)
    情况?

  1. Is there any case where created would be used over mounted?
  2. What can I use the created event for, in real-life (real-code)situation?


推荐答案

created():由于选项的处理已完成,您可以访问被动的数据属性,并根据需要进行更改。在这个阶段,尚未安装或添加DOM。所以你不能在这里做任何DOM操作

created() : since the processing of the options is finished you have access to reactive data properties and change them if you want. At this stage DOM has not been mounted or added yet. So you cannot do any DOM manipulation here

mounted():在装载或渲染DOM之后调用。在这里你可以访问DOM元素并且可以执行DOM操作,例如获取innerHTML:

mounted(): called after the DOM has been mounted or rendered. Here you have access to the DOM elements and DOM manipulation can be performed for example get the innerHTML:

console.log(element.innerHTML)

所以你的问题:


  1. 是否有任何创建将被用于安装的情况?

  1. Is there any case where created would be used over mounted?

Created通常用于从后端API获取数据并将其设置为数据属性,如 wostex 所述。但是在SSR 的mount()中不存在钩子,你需要执行诸如仅在创建的钩子中获取数据的任务

Created is generally used for fetching data from backend API and setting it to data properties as wostex commented . But in SSR mounted() hook is not present you need to perform tasks like fetching data in created hook only


  1. 在实际(实际代码)情况下,我可以将创建的事件用于什么?

  1. What can I use the created event for, in real-life (real-code) situation?

用于从外部API获取要呈现的任何初始所需数据(如JSON)并将其分配给任何被动数据属性

For fetching any initial required data to be rendered(like JSON) from external API and assigning it to any reactive data properties

data:{
    myJson : null,
    errors: null
},
created(){
    //psuedo code
    database.get().then((res) => {
        this.myJson = res.data;
    }).catch((err) => {
        this.errors = err;
    });
}

这篇关于Vue.js中创建和挂载事件之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 03:49