1.App.vue程式碼如下:
<template> <button @click="change">切換元件</button> <p></p> <keep-alive> <component :is="tabComponent"></component> </keep-alive> </template> <script> import {defineAsyncComponent} from "vue" import Child1 from "./view/Child1.vue" const Child2 = defineAsyncComponent( ()=>import('./view/Child2.vue'), ) // import Child2 from "./view/Child2.vue" export default { data() { return { tabComponent: "Child1" } }, components: { Child1, Child2 }, methods: { change() { console.log('change', this.tabComponent == "Child1") this.tabComponent = this.tabComponent == "Child1" ? "Child2" : "Child1"; } } } </script>
2、Child1.vue程式碼如下:
<template> <div>我是子頁面1</div> <p>{{ msg }}</p> <button @click="change">切換元件</button> </template> <script> export default { data() { return { msg: '子頁面1初始資料' } }, mounted() { console.log('mounted') }, unmounted() { console.log('unmounted') }, methods: { change() { this.msg = '子頁面1改變資料' } }, } </script>
3、Child2.vue程式碼如下:
<template> <div>我是子頁面2</div> <p>{{ msg }}</p> <button @click="change">切換元件</button> </template> <script> export default { data() { return { msg: '子頁面2初始資料' } }, mounted() { console.log('mounted') }, unmounted() { console.log('unmounted') }, methods: { change() { this.msg = '子頁面2改變資料' } }, } </script>
4、效果如下: