生命周期函数

39 阅读1分钟
  • beforeCreate=>在new Vue()这个对象正要创建时触发运行,所以this对象中还不能访问到数据,这个期间能做网络请求,但是不能设置到数据源中,因为this还在创建;可以做像预加载这类任务
  • Create=>new Vue()对象创建完成,但是但是还没有挂载到DOM树中,所以只能操作this,不能操作DOM
  • beforeMount=>new Vue()对象创建完成,正要挂载的时候触发(可请求首屏数据)
  • Mount=>DOM树已经加载完成,Vue()对象已经挂载到页面上
  • beforeUpdate=>数据源已经更新了,数据正要重新渲染时触发
  • Update=>数据已经重新渲染了触发
  • beforeDestroy=>new Vue()对象销毁之前触发,this还能做最后的操作(可以保存用户的行为配置文件:播放器的进度等)
  • Destroy=>后面在webpack环境下操作,this已经销毁,无法操作this
   <div id="app">
            <div @click="fn">{{msg}}</div>
        </div>
        <script>
            new Vue({
                el: "#app",
                data: {
                    msg: "cccc"
                },
                methods: {
                    fn(){
                        this.msg="dddd"
                    }
                },
                beforeCreate() {
                    console.log("beforeCreate");
                },
                created() {
                    console.log("Create");
                },
                beforeMount() {
                    console.log("beforeMount");
                },
                mounted() {
                    console.log("Mount");
                },
                beforeUpdate() {
                    console.log("beforeUpdate");
                },
                updated() {
                    console.log("Update");
                },
                beforeDestroy() {
                    console.log("beforeDestroy");
                },
                destroyed() {
                    console.log("Destroy");
                },
            })
        </script>

image.png

image.png