你真的搞懂VUE了吗?来,做道面试题吧!

直接上题:

const MockComponent = {
    render(){
        return this.$slots.default;
    },
    data(){
        return {
            status:'',
        };
    },
    watch:{
        status:{
            handler(newVal){
                console.log('Status update:'+newVal);
            },
            immediate:true
        }
    },
    beforeCreate() {
        this.status = 'initializing';
    },
    mounted(){
        this.status = "online";
    },
    beforeDestroy() {
        this.status = 'offline';
    }
};
new Vue({
    el:"#app",
    components:{
        MockComponent,
    },
    template:`
        <div>
            <MockComponent v-if="showComponent"></MockComponent>
        </div>
    `,
    data(){
        return {
            showComponent:false,
        }
    },
    mounted() {
        this.showComponent = true;
        window.setTimeout(()=>{
            this.showComponent = false;
        },1000)
    }
})

奉上输出结果:
Status update:
Status update:online

上面这道题让我们懂得了以下几点:
1、通过v-if是可以对组件进行销毁操作的。
2、immediate:true,初始值时会执行handler。
3、在beforeCreate与beforeDestroy钩子中修改数据是不会触发watch的。
—————END—————
喜欢本文的朋友们,欢迎关注公众号 张培跃,收看更多精彩内容!!!

发布了126 篇原创文章 · 获赞 401 · 访问量 24万+

猜你喜欢

转载自blog.csdn.net/u012149969/article/details/105460785
今日推荐