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

Code example analysis of key keep-alive in Vue

不言
不言Original
2018-09-18 14:38:451654browse

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>

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!

Statement:
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