keep-alive
父组件 : <template> <div class="app"> <div class="view"> <!-- include: 组件的名称来自于组件定义时name选项 --> <keep-alive include="home,about"> <component :is="currentTab"></component> </keep-alive> </div> </div> </template> <script> import Home from './views/Home.vue' import About from './views/About.vue' import Category from './views/Category.vue' export default { components: { Home, About, Category }, data() { return { tabs: ["home", "about", "category"], // currentIndex: 0 currentTab: "home" } }, methods: { itemClick(tab) { this.currentTab = tab }, homeClick(payload) { console.log("homeClick:", payload) } } } </script> <style scoped> .active { color: red; } </style>
子组件 : <template> <div> <h2>Home组件</h2> <h2>当前计数: {{ counter }}</h2> <button @click="counter++">+1</button> </div> </template> <script> export default { name: "home", data() { return { counter: 0 } }, created() { console.log("home created") }, unmounted() { console.log("home unmounted") }, // 对于保持keep-alive组件, 监听有没有进行切换 // keep-alive组件进入活跃状态 activated() { console.log("home activated") }, deactivated() { console.log("home deactivated") } } </script> <style scoped> </style>
本文来自博客园,作者:杨建鑫,转载请注明原文链接:https://www.cnblogs.com/qd-lbxx/p/16615092.html