Home > Web Front-end > JS Tutorial > Code example analysis of key keep-alive in Vue

Code example analysis of key keep-alive in Vue

不言
Release: 2018-09-18 14:38:45
Original
1664 people have browsed it

The content of this article is about the code example analysis of key keep-alive in Vue. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

keep-alive key

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="./vue.js"></script>
</head>
<body>
    <p id="app">
        <keep-alive>
            <child-component key="1" v-if="seen" name="1"></child-component>
            <child-component key="2" v-if="!seen" name="2"></child-component>
        </keep-alive>
        <button @click="toggle">toggle</button>
    </p>
    <script type="text/javascript">
        Vue.component('child-component', {
            template: `<input type="text" placeholder="enter">`,
            data() {
                return {}
            },
            props: ["name"],
            mounted() {
                console.log(`${this.name} mounted`)
            }
        })
        const vm = new Vue({
            el: "#app",
            data: {
                seen: true
            },
            methods: {
                toggle() {
                    this.seen = !this.seen;
                }
            }
        })
    </script>
</body>
</html>
Copy after login

Key is the identification element that will no longer be reused. Note that key is a reserved attribute in Vue and cannot be passed to sub-components as props, otherwise it will be in the control I saw Vue's error

but the keep-alive flag does not create component instances repeatedly, that is, it will only trigger the created mounted event once.

You can use both The reuse of components is managed more carefully

The above is the detailed content of Code example analysis of key keep-alive in Vue. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template