关于vue钩子函数的探究

2018-05-25  本文已影响81人  喵呜Yuri
image.png

理论很详尽,今天来探究一下理论之后的实践部分,即这些钩子函数的应用场景和具体用法。因为在平时我也就是mounted用的比较多一点而已。
html模板部分

 <p class="testp" @click="updateFn">{{message}}</p>

数据data部分

data () {
    return{
      message : "xuxiao is boy"
    }
}

beforeCreate

这之中:
this.$data
this.message
$('.testp')
都是undefined并不存在的

那看到这个函数有一项“init”描述,测试一下

  beforeCreate:function () {
    console.log(this.$data);
    this.message = 'hello';
    alert(this.message);
    console.log($('.testp'));
  }
image.png

点击确定


image.png

只能说“hello”的初始化赋值存在过。感觉好无力啊哈哈哈哈

created

  created:function () {
    console.log(this.$data);//有了
    console.log(this.message);//有了
    console.log($('.testp'));//length =0
  }

此时只有dom还未渲染,适用于组件内需要ajax获取数据,那么就可以在create时使用ajax,正好用于获取数据。

beforeMounted

跟created一样的

mounted

  mounted: function () {
    console.log(this.$data);//ok
    console.log(this.message);//ok
    console.log($('.testp'));//ok
  }

在这个函数中可以操作DOM了

beforeUpdate& Update

  beforeUpdate:function () {
    console.log(this.$data);
    console.log(this.message);
    console.log($('.testp'));
  },
  updated:function () {
    console.log(this.$data);
    console.log(this.message);
    console.log($('.testp'));
  },

点击元素,使元素改变会同时触发beforeUpdate& Update里面的方法

上一篇 下一篇

猜你喜欢

热点阅读