Vue3动态组件/异步组件


一、动态组件

动态切换组件
代码如下(示例):

<template>
  <ul>
  <li v-for="(item,index) in list" :key="index" @click="change(index)">{{item.name}}</li>
  </ul>
  <keep-alive>
    <component :is="currentComponent.com"></component>
  </keep-alive>
</template>

<script setup>
import CommonC from '../components/CommonC.vue'
import CommonB from '../components/CommonB.vue'
import CommonA from '../components/CommonA.vue'

let list = reactive([
  {name:"切到A",com:markRaw(CommonA)},
  {name:"切到B",com:markRaw(CommonB)},
  {name:"切到C",com:markRaw(CommonC)}
])

let currentComponent = reactive({
  com:list[0].com
})
const change=(idx)=>{
  currentComponent.com = list[idx].com
}
</script>

1.markRaw

标记一个普通对象,使得它不可以被转换成响应式对象。简单来说,就是组件不需要响应式,这样可以提高性能。

2.keep-alive

组件在非活动状态,依旧保持组件的实例。即组件被切换时,状态不会被重置。
当一个组件实例从 DOM 中移除但它是由 缓存的组件树的一部分时keepalive,它会进入停用状态而不是被卸载。当组件实例作为缓存树的一部分插入 DOM 时,它会被激活。
保持活动状态的组件可以使用onActivated()和为这两种状态注册生命周期钩子onDeactivated()

二、异步组件

1.使用官方提供的defineAsyncComponent()函数

代码如下(示例):

<template>
    <common-a></common-a>
    <common-b></common-b>
  <div>
  //C组件为图片资源
    <common-c></common-c>
  </div>
</template>

<script setup>
import CommonB from '../components/CommonB.vue'
import CommonA from '../components/CommonA.vue'

const CommonC = defineAsyncComponent(() =>
  import('../components/CommonC.vue')
)
</script>

在这里插入图片描述
我们可以看到视口还没加载到img就直接加载出来了。

2.使用插件vueuse

代码如下(示例):

<template>
    <common-a></common-a>
    <common-b></common-b>
  <div ref="target">
    <common-c v-if="targetIsVisible"></common-c>
  </div>
</template>

<script setup>
import { useIntersectionObserver } from '@vueuse/core'
// import CommonC from '../components/CommonC.vue'
import CommonB from '../components/CommonB.vue'
import CommonA from '../components/CommonA.vue'

const CommonC = defineAsyncComponent(() =>
  import('../components/CommonC.vue')
)
const target = ref(null)
const targetIsVisible = ref(false)

const { stop } = useIntersectionObserver(
  target,
    ([{ isIntersecting }], observerElement) => {
      console.log(isIntersecting);
      if(isIntersecting){
        targetIsVisible.value = isIntersecting
      }
      
      },
    )
</script>

isIntersecting 可以判断组件是否出现在视口,初始值为false,当组件出现在视口就会加载其组件。
在这里插入图片描述
异步组件在不使用插件的情况下,他会按需加载组件需要的js文件


  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值