Differences and created a life cycle mounted.

First, what is the life cycle?

In plain language, that is, Vue instance of the component or process from creation to destroy a series of intermediate passes. Although less rigorous, but also basically understandable.
Through a series of practice, now all the problems of the sort again, today recorded about the difference between the created and mounted:

 

Two, created and mounted the difference?

Official diagrammed below:

We seen two nodes from the map:
created: the template rendered before calling html, which is usually initialize certain property values, and then rendered into view.
mounted: After rendering the template into html calls, usually after page initialization is complete, and then the html dom node performs some operations needed.
In fact, both of better understanding, typically created using multiple times, and is usually mounted in use to use or to operate some of the plug-in components, such as the use of plug chart.js:  var = document.getElementById CTX (ID); usually this step will be, but if you write components, you will find it impossible to chart some initial configuration created in, we have to wait until after this html rendering can be carried out, then mounted is the best choice. See the following example of a (a component).

Third, examples

 
[javascript]  view plain  copy
 
 
  1. <span style="font-size:14px;">Vue.component("demo1",{  
  2.         data:function(){  
  3.             return {  
  4.                 name:"",  
  5.                 age:"",  
  6.                 city:""  
  7.             }  
  8.         },  
  9.         template:"<ul><li id='name'>{{name}}</li><li>{{age}}</li><li>{{city}}</li></ul>",  
  10.         created:function(){  
  11.             this.name="唐浩益"  
  12.             this.age = "12"  
  13.             this.city ="杭州"  
  14.             var x = document.getElementById("name")//第一个命令台错误  
  15.             console.log(x.innerHTML);  
  16.         },  
  17.         mounted:function(){  
  18.             var x = document.getElementById("name")/</span>/第二个命令台输出的结果<span style="font-size:14px;">  
  19.             console.log(x.innerHTML);  
  20.         }  
  21.     });  
  22.     var vm = new Vue({  
  23.         el:"#example1"  
  24.     })</span>  
可以看到输出如下:

可以看到都在created赋予初始值的情况下成功渲染出来了。
但是同时看console台如下:

可以看到第一个报了错,实际是因为找不到id,getElementById(ID) 并没有找到元素,原因如下:
在created的时候,视图中的html并没有渲染出来,所以此时如果直接去操作html的dom节点,一定找不到相关的元素

而在mounted中,由于此时html已经渲染出来了,所以可以直接操作dom节点,故输出了结果“唐浩益”。

以上就是我自己总结的mounted和created的区别,写的比较简陋,记录下来,加深印象。

转自 https://blog.csdn.net/xdnloveme/article/details/78035065

 

Guess you like

Origin www.cnblogs.com/2001-/p/11811992.html