0
点赞
收藏
分享

微信扫一扫

Vue 生命周期图解

image.png

  • beforeCreate()无法通过vm访问到data中的数据、methods中的方法
  • created():可以通过vm访问data中的数据、methods中配置的方法
  • beforeMount():
    • 页面呈现未经Vue编译的DOM结构
    • 所有对DOM的操作,最终不奏效
  • mounted():
    • 页面呈现经过Vue编译的DOM结构
    • 所有对DOM的操均有效(尽可能避免)一般在此进行开启定时器、发送网络请求、订阅消息、绑定自定义事件等初始化操作
  • beforeDestroy():vm中所有的data、methods、指令等都处于可用状态,马上要执行销毁过程,一般在此阶段执行关闭定时器、取消订阅消息、解绑自定义事件等收尾工作
  • Destoryed():已销毁
  • beforeUpdate():值是新的,页面是旧的,即:页面和值未保持同步
  • updated():值是新的,页面也是新的,即:页面和值保持同步

验证代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>模板语法</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
    <!-- 准备好一个容器 -->
    <div id="app">
        <h2>当前的n值:{{n}}</h2>
        <button @click="add">n++</button>
        <button @click="bye">掉我销毁Vue</button>
    </div>

    <script type="text/javascript">
        Vue.config.productionTip = false // 阻止vue在启动是提示生产
        new Vue({
            // 无法访问data数据
            beforeCreate() {
                console.log('1-beforeCreate')
                console.log(this)
                debugger;
            },
            created() {
                console.log('2-created')
                console.log(this)
                debugger;
            },
            el:'#app',
            data:{
                n:1,
            },
            methods: {
                add(){
                    this.n++;
                },
                bye(){
                    console.log('bye')
                    this.$destroy()
                }
            },
            beforeMount() {
                console.log('3-beforeMount')
                this.n = 100;
                debugger;
            },
            mounted(){
                console.log('4-mounted')
                debugger; 
            },
            beforeDestroy() {
                console.log('5-beforeDestroy')
                console.log('n = ' + this.n)
                debugger; 
            },
            destroyed() {
                console.log('6-destroyed')
                console.log('n = ' + this.n)
                debugger; 
            },
            beforeUpdate() {
                console.log('beforeUpdate')
                console.log('n = ' + this.n)
                debugger;
            },
            updated() {
                console.log('updated')
                console.log('n = ' + this.n)
                debugger;
            },

        })
    </script>

</body>
</html>

(1)验证beforeCreate()

image.png

(2)验证create()

image.png

(3)验证beforeMount()

image.png

(4)验证mounted()
image.png

(5)验证beforeUpdate()

image.png

(6)验证updated()
image.png

(7)验证beforeDestroy()

image.png

(8)验证destroyed()

image.png

举报

相关推荐

0 条评论