• Vue的八大生命周期钩子函数


     /* Vue实例化对象创建之前 */

    beforeCreate:Vue实例化对象创建之前,获取不到data里面的数据的

    created:Vue实例化对象创建之后,可以获取data里面的数据,不可以获取到dom包括根节点

    1. "app">
    2. <h1>{{msg}}h1>
  • <script src="./vue.min.js">script>
  • <script>
  • new Vue({
  • el: "#app",
  • data: {
  • msg: "前端工作"
  • },
  • // 最先执行的函数
  • beforeCreate: function () {
  • console.log("vue实例化对象创建之前");
  • // console.log(this.msg);
  • },
  • created() {
  • console.log("vue实例化对象创建之后");
  • console.log(this.msg);
  • console.log(document.querySelector("#app"));
  • // created 在生命周期里面不可能获取节点
  • console.log(this.$el);
  • // ⭐一般用来获取接口数据,速度更快,因为这个时候已经获取到data的数据了
  • setTimeout(() => {
  • this.msg = "从接口获取的数据"
  • }, 100)
  • },
  • beforeMount() {
  • // beforeMount 在生命周期里面可获取节点,但是不能显示出data数据
  • console.log('beforeMount', this.$el);
  • },
  • mounted() {
  • // ⭐操作元素节点的时候,写在mounted
  • console.log('mounted', this.$el);
  • }
  • })
  • script>
  • /* Vue的dom挂载之前 */

    beforeMount:dom挂载之前可以获取到根节点,还没有把data中的数据渲染到dom节点上

    mounted:已经把data中的数据渲染到了dom节点上

    1. beforeMount() {
    2. // beforeMount 在生命周期里面可获取节点,但是不能显示出data数据
    3. console.log('beforeMount', this.$el);
    4. },
    5. mounted() {
    6. // 操作元素节点的时候,写在mounted
    7. console.log('mounted', this.$el);
    8. this.id = setInterval(() => {
    9. this.num++;
    10. console.log(this.num);
    11. }, 1000)
    12. },

    /* 当把Vue实例中的data中的值改变了会触发beforeUpdate和updated */

    beforeUpdate在生命周期里面可获取节点,但是不能显示出data数据

    updated操作元素节点的时候,写在mounted

    1. // 在data更新之前执行
    2. beforeUpdate() {
    3. console.log('beforeUpdate', this.msg, this.$el);
    4. },
    5. updated() {
    6. console.log('beforeUpdate', this.msg, this.$el);
    7. },

     /* Vue组件销毁前 */

    beforeDestroy:在调用$destroy()方法的时候 会执行下面的两个钩子函数

    destroyed:/* ★beforeDestroy和destroyed的一个使用场景是在销毁定时器节约内存的时候都可以使用 */

    1. beforeDestroy() {
    2. clearInterval(this.id)
    3. console.log('beforeDistory', this.msg, this.$el);
    4. },
    5. destroyed() {
    6. // clearInterval(this.id)
    7. console.log('destory', this.msg, this.$el);
    8. },
    9. methods: {
    10. changeFn() {
    11. this.msg = "111111111111111111"
    12. },
    13. destroyFn() {
    14. this.$destroy()
    15. }
    16. }

  • 相关阅读:
    强化学习中值的迭代
    L2研发工程师—牛客网
    【电力系统】含电热联合系统的微电网运行优化附matlab代码和复现论文
    3ds max文件打包?max插件CG Magic一键打包整起!
    相机标定基本原理
    【linux/shell案例实战】shell界面命令快捷键
    Ubuntu Linux 定时 执行 Shell脚本 自动备份数据库
    Seata概述
    docker部署完mysql无法连接
    虚拟机里为什么桥接模式可以广播,NAT模式不能广播?
  • 原文地址:https://blog.csdn.net/SYQ15544423296/article/details/126055487