created():在创建vue对象时,当html渲染之前触发;但是注意,全局vue.js不强制刷新或者重启时只创建一次,也就是说,created()只会触发一次;

activated():在vue对象存活的情况下,进入当前存在activated()函数的页面时,一进入页面就触发;可用于初始化页面数据、keepalive缓存组件后,可执行方法;

deactivated():离开组件时执行;

注意:activated()和deactivated()只有在<keep-alive></keep-alive>包裹的时候才有效;

例:

新建两个组件,compA,compB:

<template>
<div class="app">
    我是组件A
</div>
</template>

<script>
    export default{
        name: "compA",
        data(){
            return {
               
            }
        },
        created(){
            console.log('created');
        },
        activated(){
            console.log('activated');
        },
        deactivated(){
            console.log('deactivated');
        }
    }
</script>

同理建compB;

在view中引用两个组件:

<template>
<div class="app">
    <div class="bth">
        <button @click="currentComponent='compA'">A</button>
        <button @click="currentComponent='compB'">B</button>    
    </div>
</div>
<keep-alive>
    <component :is="currentComponent"></component>
</keep-alive>
</template>

<script>
    import compA from './component/compA'
    import compB from './component/compB'
    export default{
        name: "App",
        component: {
            compA, compB
        },
        data(){
            return {
                currentComponent: 'compA'
            }
        }
    }
</script>

在点击切换B组件时,A组件的deactivated()会执行;

注::is后绑定组件名,渲染当前组件;

Logo

前往低代码交流专区

更多推荐