1、App.vue代码如下:
<template> <button @click="change">切换组件</button> <p></p> <keep-alive> <component :is="tabComponent"></component> </keep-alive> </template> <script> import Child1 from "./view/Child1.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、效果如下:
标签:Child1,Child2,vue,console,log,alive,keep,Vue3,msg From: https://www.cnblogs.com/tianpan2019/p/18353882