• 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. }

  • 相关阅读:
    【Linux】简化自用-Win10安装VMware和CentOS
    【数据仓库-零】数据仓库知识体系 ing
    redis 哨兵,高可用的执行者
    wxpython设计GUI:窗口Frame最大化、最小化、关闭及全屏显示的说明
    3台平行机上带有2个服务等级的离线负载均衡
    win11安装教程(附tpm2.0开启或跳过教程)
    React 入门:组件实例三大属性之refs
    Unity 使用Sqlite
    【区块链 | 智能合约】如何编写一个可升级的智能合约
    HIN应用调研总结
  • 原文地址:https://blog.csdn.net/SYQ15544423296/article/details/126055487