动态组件切换及其Vue提供的is属性和keep-alive高性能组件

动态组件

  1. 什么是动态组件?
    可以改变的组件
  2. 使用
    通过 Vue 提供了一个 component + is 属性
  3. 动态组件指的就是 component这个组件
  4. 案例
    <div id="app">
       <button @click = "change"> 切换 </button>
       <keep-alive include="">
          <component :is = "type"></component>
       </keep-alive>
    </div>
    
      Vue.component('Aa',{
          template: '<div> Aa </div>'
       })
    
       Vue.component('Bb',{
          template: '<div> Bb </div>'
       })
    
       new Vue({
          data: {
             type: 'Aa'
          },
          methods: {
             change () {
             this.type = (this.type === 'Aa'?'Bb':'Aa')
             }
          }
       }).$mount('#app')
    
  5. Vue提供了一个叫做 keep-alive 的组件可以将我们的组件进行浏览器缓存,这样当我们切换组件时,就可以大大提高使用效率
  6. keep-alive也可以以属性的形式呈现,但是我们如果搭配component的话,建议使用组件的形式

---------------------------------------------若有疑虑详见Vue进阶Day02

### Vue3 中 `keep-alive` 的使用方法及最佳实践 在 Vue3 中,`keep-alive` 是一个内置的抽象组件,用于缓存不活动的组件实例,避免重复渲染,从而提高性能[^2]。以下是 `keep-alive` 的详细用法一些最佳实践。 #### 1. 基本用法 在 Vue3 中,`keep-alive` 的基本用法是将需要缓存的动态组件包裹起来。例如: ```vue <template> <keep-alive> <component :is="currentComponent"></component> </keep-alive> </template> ``` 这里,`currentComponent` 是一个动态组件,通过 `keep-alive` 包裹后,该组件的状态会被缓存[^2]。 #### 2. 在路由中使用 `keep-alive` 在 Vue Router 中,可以通过 `router-view` `keep-alive` 结合来缓存路由组件Vue3 中的写法与 Vue2 略有不同,推荐使用以下方式: ```vue <template> <router-view v-slot="{ Component }"> <keep-alive> <component :is="Component" /> </keep-alive> </router-view> </template> ``` 这种方式可以确保路由切换时,组件状态被正确缓存[^3]。 #### 3. 条件缓存 如果只需要缓存某些特定的组件,可以使用 `include` `exclude` 属性。这两个属性支持字符串、正则表达式或数组形式。 ```vue <template> <keep-alive include="Home,About" exclude="Settings"> <router-view v-slot="{ Component }"> <component :is="Component" /> </router-view> </keep-alive> </template> ``` 上述代码中,`Home` `About` 组件会被缓存,而 `Settings` 组件不会被缓存。 #### 4. 注意事项 - **缓存清理**:长时间运行的应用可能会导致内存占用过高,因此需要根据需求手动清除缓存。可以通过 `activated` `deactivated` 生命周期钩子来管理缓存逻辑。 - **性能优化**:不要对所有组件进行缓存,仅对需要保留状态的组件使用 `keep-alive`。 - **Vue3 新特性**:在 Vue3 中,`keep-alive` 的写法发生了变化,使用 `v-slot` 是推荐的方式[^3]。 #### 5. 示例代码 以下是一个完整的示例,展示如何在 Vue3 中使用 `keep-alive` 缓存路由组件: ```vue <template> <div id="app"> <keep-alive include="Home,About"> <router-view v-slot="{ Component }"> <component :is="Component" /> </router-view> </keep-alive> </div> </template> <script> export default { name: "App", }; </script> ``` ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值