Home > Article > Web Front-end > Code example analysis of key keep-alive in Vue
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.
<!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!