zoukankan      html  css  js  c++  java
  • vue系列生命周期(四)

    vue生命周期,是指vue实例从创建到销毁的一个过程,掌握了这个过程中各个阶段的状态,就能合理使用,是我们的程序性能更高,开发更合理,减少bug。
    我们先看一张官方的vue的生命周期的图:
    vue生命周期
    可以看到,vue实例生命周期分为:beforeCreate,created,beforeMount,mounted,beforeUpdate,updated,activated,deactivated,beforeDestroy,destroyed,errorCaptured。下面我们再看看各个周期的含义,及平常我们的用途。
    各个周期的作用

    这里说明一下,createdmounted2个阶段的区别。created的时候,dome节点并没有加载,如果做一些dome从操作,如document.getElementById时是获取不到元素的。mounted能获取到dome节点,但也不完全加载完,完全加载完可以放到this.$nextTick()的回调里面。

    下面看一个完整的实例,来表明各个周期的执行情况。

    <!doctype html>
    <html lang="en">
    <head>
        <title>vue生命周期测试</title>
    </head>
    <body>
    <div id="test">
        <h3>单组件</h3>
        <span>{{testData}}</span>
        <button @click="testData += 1">更新data里面的值</button>
        <button @click="destroyVue">销毁VUE实例</button>
    </div>
    </body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17-beta.0/vue.js"></script>
    <script>
        new Vue({
            el: "#test",
            data() {
                return {
                    testData: 0
                }
            },
            beforeCreate() {
                console.log("beforeCreate")
            },
            created() {
                console.log("created")
            },
            beforeMount() {
                console.log("beforeMount")
            },
            mounted() {
                console.log("mounted")
            },
            beforeUpdate() {
                console.log("beforeUpdate")
            },
            updated() {
                console.log("updated")
            },
            beforeDestroy() {
                console.log("beforeDestroy")
            },
            destroyed() {
                console.log("destroyed")
            },
            methods: {
                destroyVue() {
                    this.$destroy()
                }
            }
        })
    </script>
    </html>
    

    可以看到vue实例创建时,马上执行了:
    创建执行
    我们点击按钮,更新data里面的数据是,执行了下面的钩子:
    更新data
    我们再销毁vue实例,执行情况如下:
    销毁
    上面的实例可以看到各种钩子的执行情况,了解各个钩子的作用和执行时机,合理运用,有助于我们的合理开发。
    想看更多文章,可以关注我的个人公众号:
    公众号

  • 相关阅读:
    总结:工作 + 学习 (2019年)
    JVM 理解性学习(一)
    渗透神器cobalt strike在数字杀软环境下的使用
    普通路由器刷开源固件DD-WRT的简单过程
    云烟渗透题总结
    对thinkphp5.0框架的实例学习
    内网渗透 关于GPO
    简单尝试利用维控LeviStudioU的一栈缓冲区溢出漏洞
    试写foxit reader的ConvertToPDF功能的wrapper
    第05章下 加载内核
  • 原文地址:https://www.cnblogs.com/zhujieblog/p/12816872.html
Copyright © 2011-2022 走看看