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

问题描述

Vue.js 文档对 createdmounted 事件的描述如下:

已创建

在实例创建后同步调用.在这阶段,实例已经完成了对选项的处理,这意味着已设置以下内容:数据观察、计算属性、方法,观察/事件回调.然而,安装阶段还没有已启动,$el 属性尚不可用.

已安装

在实例刚刚挂载到 el 被替换的地方后调用通过新创建的 vm.$el.如果根实例挂载到文档内元素,vm.$el 也将在安装时在文档内叫.

在服务器端渲染期间不会调用此钩子.

我理解理论,但我有2个问题关于实践:

  1. 是否存在将 created 用于 mounted 之上的情况?
  2. 在现实生活中,我可以将 created 事件用于什么(真实代码)情况?
解决方案

created() : 由于选项的处理已完成,您可以访问响应式 data 属性并根据需要更改它们.在这个阶段,DOM 还没有被挂载或添加.所以你不能在这里做任何 DOM 操作

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

console.log(element.innerHTML)

所以你的问题:

  1. 在任何情况下,created 会被过度安装使用吗?

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

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

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

数据:{myJson:空,错误:空},创建(){//伪代码database.get().then((res) => {this.myJson = res.data;}).catch((错误) => {this.errors = 错误;});}

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

created
mounted

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

  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() : 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(): 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)

So your questions:

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

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

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

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(){
    //pseudo code
    database.get().then((res) => {
        this.myJson = res.data;
    }).catch((err) => {
        this.errors = err;
    });
}

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

10-20 07:12