039.Vue3入门,异步加载组件,初始时不全部加载,使用时才加载

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、效果如下:

 

posted @ 2024-08-12 00:32  像一棵海草海草海草  阅读(236)  评论(0)    收藏  举报