前言
vue的征战开始了,纠结了很久到底是学Vue还是React,然后发现有纠结那么久的时间,说不定一个已经入门了。于是先挑一个基于原生js的框架Vue开始吧(还有个主要原因是Vue的中文官网做的比较小清新,看起来舒服).
生命周期
如上图所示,Vue的生命周期一共有"Create","Mount","Update","Destroy"四个步骤。
vue.js提供了以下8个生命周期钩子函数,给我们提供了执行自定义逻辑的机会:
- beforeCreate
- created
- beforeMount
- mounted
- beforeUpdate
- updated
- beforeDestroy
- destroyed
从字面很好理解分别是创建前后,挂接前后,更新前后,销毁前后
注:所谓的mount个人理解就是用vue.js的el去替换dom元素。
用个最简单的demo说明:
html:
<div id="vm1" >{{data}}</div>
javascript:
var vmData = { name:"vmData", a:"999", data:"this is data" }; var log = function(msg){ console.log(msg); }; var vm = new Vue( { el:"#vm1", data:vmData, beforeCreate:function(){log("beforeCreate")}, created:function(){log("created")}, beforeMount:function(){log("beforeMount")}, mounted:function(){log("mounted")}, beforeUpdate:function(){log("beofreUpdate")}, updated:function(){log("updated")}, beforeDestroy:function(){log("beforeDestroy")}, destroyed:function(){log("destroyed")} }); vmData.b = "998"; vm.$watch("a",function(oldVal,newVal){ console.log("oldVal:" + oldVal + ";newVal:" +newVal); });
在页面初次加载时,会触发"create"和"mount"生命周期钩子:
在控制台中修改data中的值,以及调用$destroy()方法,分别会触发"update"和"destroy"生命周期钩子: