VUE3之Component(三)

生命周期

在某一个生命周期的阶段时回调一个方法:

// App.vue
<template>
    <div>
        <button @click="isShow=!isShow">切换</button>
        <template v-if="isShow">
            <home></home>
        </template>
    </div>
</template>

<script>
import Home from "./Home.vue";
    export default {
        data() {
            return {
                isShow:true
            }
        },
        components:{
            Home
        }
    }
</script>
// Home.vue
<template>
    <div>
        <h2 ref="title">{{message}}</h2>
        <button @click="changeMessage">修改message</button>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                message:"hello home"
            }
        },
        methods: {
            changeMessage(){
                this.message="hello change"
            }
        },
        beforeCreate() {
            console.log("beforeCreate");
        },
        created() {
            console.log("created");
        },
        beforeMount() {
            console.log("beforeMount");
        },
        mounted() {
            console.log("mounted");
        },
        beforeUnmount() {
            console.log("beforeUnmount");
        },
        unmounted() {
            console.log("unmounted");
        },
        beforeUpdate() {
            console.log(this.$refs.title.innerHTML);
            console.log("beforeUpdate");
        },
        updated() {
            console.log(this.$refs.title.innerHTML);
            console.log("updated");
        },
    }
</script>

对于keep-alive的缓存组件,可以使用activated和deactivated来回调激活与取消的状态:

<script>
    export default {
        name:"about",
        data() {
            return {
                counter:0
            }
        },
        created() {
            console.log("about created");
        },
        unmounted() {
            console.log("about unmounted");
        },
        activated() {
            console.log("about activated");
        },
        deactivated() {
            console.log("about deactivated");
        },
    }
</script>
image 21

发表评论

您的电子邮箱地址不会被公开。