Vue dynamic components and keep alive

1. Dynamic components

Dynamic component: as the name implies, dynamic component is the display of dynamic switching components
Requirements: display different states according to different states

1.1 use v-if or v-show to switch components

The sample code is as follows:

    <style>
         *{
            margin: 0;
            padding: 0;
        }
        li{
            list-style: none;
        }
        #app{
            width: 100vw;
            height:100vh;
        }
        .option ul{
            display: flex;
            position: fixed;
            left: 0;
            right:0;
            bottom:0;
            height:50px;
            border-top:2px solid #FFCA28;
        }

      
        .option ul li{
            flex: 1;
            text-align:center;
            line-height: 50px;
            font-size:22px;
            color:#fff;
            background: #FFCA28;
        }

        .content{
            position: fixed;
            top:0;
            left:0;
            right:0;
            bottom: 52px;
            background:#C5E1A5;
            padding:30px;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="content">
            <home v-if = "current == 'Home'"></home>
            <my-com  v-if = "current == 'MyCom'"></my-com> 
            <about v-if = "current == 'About'"></about>
        </div>
        <div class="option">
            <ul>
                <li @click="handleClick('Home')">Home</li>
                <li @click="handleClick('MyCom')">Content</li>
                <li @click="handleClick('About')">About</li>
            </ul>
        </div>
    </div>
    <script>
        let Home= ({
            template:`
           		<h2>I am home assembly</h2>
           		<input type = "text">
            `,
        })

        let MyCom = {
            template:`
                <h2>Article assembly</h2>
            `,
       }

        let About= ({
            template:`
                <h2>I am About assembly</h2>
            `,
        })
        let vm = new Vue({
            el:"#app",
            data:{
                current:"Home"
            },
            methods:{
                handleClick(value){
                    this.current = value
                }
            },
            components: {
                Home,About,MyCom
            }
        })
    </script>
</body>

The display effect of the page is as follows:

Although this can achieve the effect we want, it is a very unfriendly cooking. If we have many components to switch, we need to write a lot of v-if to switch

So Vue helps us provide dynamic components to solve this problem

1.2 basic usage of dynamic components

Dynamic component is a very efficient way to switch between different components

By using the reserved < component > element and binding the is attribute, we can switch multiple components at the same mount point, and use dynamic components to rewrite the above case

Put the following code in the above case:

            <home v-if = "current == 'Home'"></home>
            <my-com  v-if = "current == 'MyCom'"></my-com> 
            <about v-if = "current == 'About'"></about> 

Replace with this code to achieve the same effect:

            <component :is="current"></component>

At this time, the value of is attribute is dynamically bound to the data attribute through the v-bind instruction. At this time, the name of which component the compiled is value is will show which component

2. Use of keep alive on dynamic components

When we switch between these components, sometimes we want to keep the state of some components, so as to avoid the problem of repeated rendering

For example, we have entered the login information on the login page, but accidentally click on the registration page. When we return to the login page, we want to keep the login information we have entered, so we need to use keep alive

Keep alive is generally used for component switching. Otherwise, components will be created and deleted frequently during component switching, which is not good. This is not the case before component switching is saved

2.1 do not use keep alive

If we don't use keep alive, we will delete the old component and render the new one every time we switch components

Each component also has its own life cycle. Let's add the life cycle function to see if every time we switch components, we are re creating and deleting components. Will we render new components first or delete old components first???

The sample code is as follows:

 <div id="app">
        <div class="content">
         	 <component :is="current"></component>
		</div>
        <div class="option">
            <ul>
                <li @click="handleClick('Home')">Home</li>
                <li @click="handleClick('MyCom')">Content</li>
                <li @click="handleClick('About')">About</li>
            </ul>
        </div>
    </div>
    <script>
        let Home= ({
            template:`
            <div>
				 <h2>I am home assembly</h2> 
				 <input type = "text" /> 
			</div>
           
            `,
            beforeCreate () {
               console.log("Home beforeCreate") 
            },
            created () {
               console.log("Home Create") 
            },
            beforeMount () {
                console.log("Home beforeMount");
            },
            mounted () {
                console.log("Home mounted");
            },
            beforeDestroy () {
                console.log("Home beforeDestroy");
            },
            destroyed () {
                console.log("Home destroyed");
            },
            activated(){
                // The current component is active,
                console.log('activate')
            },
            deactivated(){
                // Current component is not active, frozen
                console.log("deactivate")
            }
        })

        let MyCom = {
            template:`
                <h2>Article assembly</h2>
            `,
            beforeCreate () {
               console.log("MyCom beforeCreate") 
            },
            created () {
               console.log("MyCom Create") 
            },
            beforeMount () {
                console.log("MyCom beforeMount");
            },
            mounted () {
                console.log("MyCom mounted");
            },
            beforeDestroy () {
                console.log("MyCom beforeDestroy");
            },
            destroyed () {
                console.log("MyCom destroyed");
            }
        }

        let About= ({
            template:`
                <h2>I am About assembly</h2>
            `,
        })
        let vm = new Vue({
            el:"#app",
            data:{
                current:"Home"
            },
            methods:{
                handleClick(value){
                    this.current = value
                }
            },
            components: {
                Home,About,MyCom
            }
        })
    </script>

I will switch the page from home page to content page and observe the printed information:

By printing the hook functions of these lifecycles, we can find that:
When switching components, the old components will be deleted when the virtual DOM is ready to be added, and then the new DOM elements will be rendered

Because every component switch is a newly created component, which is brand new, the component state before the component switch will not be saved

2.2 use keep alive

But in this case, we prefer that the Home component instances of those tags can be cached when they are first created. To solve this problem, we can wrap its dynamic components with a < keep alive > element.

Put the following in the above example code:

<component :is="current"></component>

Replace with

            <keep-alive exclude="MyCom,About">
                <component :is="current"></component>
            </keep-alive>

Note: the content in the exclude attribute means that the components in it should not be kept alive

Carefully observe the change of vue display Content in the figure above. When we switch from home to Content or About, the display color of the home component will be lighter rather than disappear. Both Content and About will disappear. And the Content we input in the home page input will not disappear. This is the function of keep alive, which can save the current component state

Components will not be destroyed, but will always cache this

2.3 activated and deactivated

Brief introduction:

  1. Activated: called when activated by a keep alive cached component. The hook is not called during server-side rendering.
  2. Deactivated: called when deactivated by a keep alive cached component. The hook is not called during server-side rendering.

From the case study:

let Home= ({
            template:`
            <div>
                    <h2>Home assembly</h2>
                    <input type="text">
            </div> `,
             activated(){
                // The current component is active,
                console.log('activate')
            },
            deactivated(){
                // Current component is not active, frozen
                console.log("deactivate")
            }
        })

        let MyCom = {
            template:`
                <h2>Article assembly</h2>
            `,
        }

When we are on the home page, we will print activated. If we switch from home page to content page, we will print deactivated
That is, when we are on the home page, the home component is active. When we switch to other pages, the home component is inactive, that is, frozen

Tags: Vue Attribute

Posted on Sat, 13 Jun 2020 00:44:18 -0400 by Ajita