vue生命周期

简介

各种叫法:事件,生命周期函数,钩子函数……
生命周期里面的事件是不能阻止的,它只能监听。

  1. 创建vue对象有两种情况:(两种情况差不多)

(1)new Vue({}) 主动new一个对象
(2)Vue.component({}) 被动new的,他是一个组件

  1. 在正式开始创建前,执行beforeCreate

  2. 初始化等之后,即实例创建完成后立即被调用,执行created(此时还没有挂载),这时候就可以进行数据操作了,通常发起Ajax请求

  3. 判断是否有el:

    如果有,则为主动new的对象,自动挂载
    如果没有,就认为时一个组件,就执行$mount方法帮你挂载

  4. 判断是否有template:

    如果有,就编译template
    如果没有,就使用HTML标签作为template

  5. 接下来要挂载啦~

    挂载前,执行beforeMount
    挂载后,执行mounted,这时候就可以开始操作元素,子组件之类的了,只执行一次

  6. 当数据发生改变的时候,就会更新

    改变前,执行beforeUpdate
    改变后,执行updated

  7. 当你的元素被干掉了,就会销毁(例如页面没了,浏览器关了,或者被v-if删除了等等)

    干掉前,执行beforeDestroy
    干掉后,执行destroyed

  • activated 激活 被内置组件 包裹
  • deactivated 停用

测试代码

//子组件
    var test={
        template:`
我是test组件
`, data:function () { return{ 'test':'hello' } }, //生命周期开始 beforeCreate:function () { //组件创建之前 //console.log("组件创建之前"); console.log(this.text); }, created:function () { //组件创建之后自动调用 //console.log("组件创建之后"); console.log(this.text); }, //在使用组件的时候,会自动触发上面两个函数,created里面就可以操作数据 //所以,可以在created里面发送Ajax请求 beforeMount:function () { //vue已经有了,但是没找到目标元素,不起作用 //console.log("挂载之前"); console.log( document.getElementById("app").innerHTML ); }, mounted:function () { //vue起作用了 //console.log("挂载之后"); console.log( document.getElementById("app").innerHTML ); }, //vue找到目标元素 并起作用的时候,自动触发以上两个事件 beforeUpdate:function () { console.log( document.getElementById("app").innerHTML ); }, updated:function () { console.log( document.getElementById("app").innerHTML ); }, //以上两个不会自动触发,只有数据改变 才会触发 //beforeUpdate是原DOM的内容,update是改变后的内容 beforeDestroy:function () { console.log( "beforeDestroy" ); }, destroyed:function () { console.log( "destroyed" ); }, //销毁,一般结合v-if使用。一般是做一些功能的释放 //缺点:不停地销毁 创建,太浪费资源 //解决:调用vue内置组件 keep-alive activated:function () { console.log( "组件被激活" ); }, deactivated:function () { console.log( "组件被停用" ); } //以上两个必须结合keep-alive组件使用 }; var mc={ components:{ 'test':test }, data:function () { return{ flag:true } }, template:`
` }; var app=new Vue({ el:"#app", components:{ 'mc':mc } });

总而言之,我们常用的就是created和mounted。
附上一张图~


生命周期

获取DOM元素

  • 在任意标签中写 ref="xxx"
  • 通过组件对象 this.$refs.xxx 获取元素
var tempComponent={
    template:`
子组件
` } //全局组件 Vue.component('temp',tempComponent); //入口 var App={ template:`
`, beforCreat:function(){ //不能操作数据,只是初始化了事件 console.log( this.$refs.btn); //undefined }, created:function(){ //可以操作数据了 console.log( this.$refs.btn); //undefined }, beforMount:function(){ //new Vue发生装载 console.log( this.$refs.btn); //undefined }, Mount:function(){ //数据装载之后 console.log( this.$refs.btn); //获取到 console.log( this.$refs.tmp.$el); //获取xxx } } new Vue=({ el:'#app', components:{ app:App }, template:`` }),
$属性
  • $refs 获取组件内元素
  • $parent:获取当前组件对象的父组件
  • $childern:获取子组件
  • $root:获取new Vue 的实例
  • $el:组件对象的DOM元素

标签input中有指令v-if="xx",会发生变化,则我们希望在vue真正渲染DOM后,才获取

$nextTick

this.$nextTick(function(){
    this.$refs.input.focus();
});

你可能感兴趣的:(vue生命周期)