zoukankan      html  css  js  c++  java
  • 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>

    运行结果:

  • 相关阅读:
    实现input输入时智能搜索
    动态磁盘转基本磁盘(简单卷变为主分区)
    删掉一个文件夹相对于另一个文件夹多出的文件
    win10搜索不到蓝牙设备
    anaconda使用
    pycharm tab换为4个空格
    wamp端口冲突
    c++ 字符串
    pta 编程题20 旅游规划
    c++指针二维数组
  • 原文地址:https://www.cnblogs.com/lanhuo666/p/10475124.html
Copyright © 2011-2022 走看看