vue3的keepAlive缓存组件

该博客讨论了两个Vue组件——login.vue和insert.vue在页面切换时的状态管理问题。login.vue中的输入框内容在切换后丢失,而insert.vue通过onActivated生命周期钩子实现了内容保留。父组件使用keep-alive进行组件缓存,但将login.vue排除在外,以确保其状态不被保留。
摘要由CSDN通过智能技术生成

在这里插入图片描述

在这里插入图片描述

新建login.vue

 <template>
    <div>login 此界面的输入框的东西切换回来就没了
        <input type="text">
        <input type="text">
        <button @click="submit">登陆</button>
    </div>
</template>

<script setup lang="ts">

</script>
<script >
export  default{
    name:'login'
}
</script>
<style scoped>

</style>

新建insert.vue

 <template>
    <div>insert  无论切换都会保留input的内容
        <input type="text"  v-model="data.reform.text">
        <input type="text"  v-model="data.reform.password">
        <input type="text"  v-model="data.reform.code">
        <button @click="submit">注册</button>
    </div>
</template>

<script setup lang="ts">
import {reactive,onActivated}  from 'vue'
type  refo={
   reform:{
        text:string,
    password:string,
    code:string
   }
}
let  data=reactive<refo>({
    reform:{text:"",password:'',code:''}
})
onActivated(()=>{
 data.reform.code=''
})
</script>

<style scoped>

</style>

父组件引入

<template>
    <div class="content">       
    <button  @click="slectadd">切换</button>
   <keep-alive :exclude="['login']">
      <login v-if="flag"/>
      <insert v-else/>
   </keep-alive>
   </div>
</template>

<script setup lang="ts">
import  {reactive ,markRaw,ref} from 'vue'


import  login  from '../../components/login/index.vue'
import  insert  from '../../components/insert/index.vue'

const  flag=ref(true);
const  slectadd=()=>{
  flag.value=!flag.value
}
 
</script>

<style scoped lang="less">
.bg-red{
    background: red;
}
.content{
    flex: 1;
     display: flex;
    // height: 100vh;
    margin: 20px;
    border-bottom: 1px solid #ccc;
    overflow: auto;
    &-items{
        padding:20px;border-bottom: 1px solid #ffffff;
    }
     .tab{
         height: 50px;
        border:1px solid red;
     }
     component{
         height: 30px;;
     }
}
</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值