38 异步组件

发布时间 2023-10-18 17:01:40作者: 被占用的小海海

异步,需要时才被加载

<template>
  <div>
    <KeepAlive>
    <component :is="tabComponent"> </component>
    </KeepAlive>
    <button @click="change">切换组件</button>
  </div>
</template>

<script>

import ComponentA from "./components/ComponentA.vue"
// import componentB from "./components/ComponentB.vue"
import { defineAsyncComponent } from "vue"  // 引入 定义异步组件的文件
const ComponentB=defineAsyncComponent(()=>
     import("./components/ComponentB.vue")
)

  export default {
    data() {
      return {
        tabComponent: "ComponentA"
      }
    },
    methods: {
      change() {
        this.tabComponent= this.tabComponent=="ComponentA"? "ComponentB":"ComponentA"
        console.log(this.tabComponent)

      }
    },
    components: {
      ComponentA,
      ComponentB
    },
  }
</script>

<style lang="scss" scoped>

</style>