• vuejs中的生命周期


    vue中生命周期分为初始化,跟新状态,销毁三个阶段

    1.初始化阶段:beforeCreated,created,beforeMount,mounted

    2.跟新状态:beforeUpdate,update

    3.销毁vue实例:beforeDestory,destoryed

    其中created/mounted 可以用来发送ajax请求,启动定时器等异步任务

    beforeDestroy用来收尾工作,如清除定时器

    举个例子:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>09_Vue实例_生命周期</title>
    </head>
    <body>
    <div id="test">
      <button @click="destroyVue">destory vue</button>
      <p v-if="isShow">你好</p>
    </div>
    
    <script type="text/javascript" src="../js/vue.js"></script>
    <script type="text/javascript">
      new Vue({
        el: '#test',
        data: {
          isShow: true
        },
    
        beforeCreate() {
          console.log('beforeCreate()')
        },
    
        created() {
          console.log('created()')
        },
    
        beforeMount() {
          console.log('beforeMount()')
        },
    
        mounted () {
          console.log('mounted()')
          // 执行异步任务
          this.intervalId = setInterval(() => {
            console.log('-----')
            this.isShow = !this.isShow
          }, 1000)
        },
    
    
        beforeUpdate() {
          console.log('beforeUpdate()')
        },
        updated () {
          console.log('updated()')
        },
    
    
        beforeDestroy() {
          console.log('beforeDestroy()')
          // 执行收尾的工作
          clearInterval(this.intervalId)
        },
    
        destroyed() {
          console.log('destroyed()')
        },
    
        methods: {
          destroyVue () {
            this.$destroy()//触发 beforeDestroy 和 destroyed 的钩子。
          }
        }
      })
    
    
    </script>
    </body>
    </html>

    运行结果:

  • 相关阅读:
    Java static 静态代码块、代码块
    blog
    Java 类之间的关系
    vscode Cannot edit in read-only editor.
    以KNN为例用sklearn进行数据分析和预测
    Python 时间处理
    Python map filter reduce enumerate zip 的用法
    Python列出文件夹中的文件
    Java类只加载一次的情况
    Powershell 中的管道
  • 原文地址:https://www.cnblogs.com/lanhuo666/p/10475124.html
Copyright © 2020-2023  润新知