vue 动态组件名_vue-动态组件

a5370b29f40d4001598f220c8815715e.png

动态组件 keep-alive

在实现切换效果时,你会想保持在目标位置的状态,就是你在a选项看到第8行,切换到b选项后在切换到a选项里面还在第8行的位置。

(1)创建两个组件

home.vue

<template>
  <div> 
    Home
  </div>
 </template>
<script>
export default {
  name:"Home"
}
</script>

news.vue

<template>
  <div> 
    News:{{ msg }}
    <button @clack="updateMsg">改变</button>
  </div>
 </template>
<script>
export default {
  name:"News",
  data(){
    return{
      msg:"我是初始化值"
    }
  },
  methods:{
    updateMsg(){
      this.msg = "我是改变了的值"
    }
  }
}
</script>
<style>
</style>

(2)主页面引入home.vue 和 news.vue

<template>
  <div> 
    App
     <component :is="currentComponent"></component>
     <button @click="chengeView">切换视图</button>
  </div>
 </template>
<script>
import Home from './home'
import News from './news'
export default {
  name:"App",
  data(){
    return{
    //默认值显示Home
      currentComponent:Home ,
      //定一个默认值进行取反
      flag:false
    }
  },
  compinents:{
    Home,
    News 
  },
  methods:{
    chengeView(){
      if(this.flag){
        this.currentComponent = Home
        this.flag = false
      }else{
        this.currentComponent = News 
        this.flag = true
      }
    }
  }
}
</script>
<style>
</style>

功能创建好后

1.点击切换视图到News

7933b1c6c478dc6d1e91a28866f3d352.png

2.点击改变

ab985c7c29c1409b2faeb67fd185f4a4.png

3.到了我是改变了的值,在点击切换视图

6ae05105417fe29cf5db74238e9fe2a0.png

4.到home,在点击切换视图

7418d02183ff1b67de4df4dce9e87976.png

5.这时候发现到了我是初始化页面,不会回到我是改变了的值页面

dfc95330b383dfe2310e7e5605b228bb.png

这样会增加性能消耗,实现缓存效果,在加载组件的位置增加keep-alive,这样就不会增加性能的消耗,这就是动态组件keep-alive的作用。keep-alive缓存操作不仅可以用在component上,还可以用于路由上。

<template>
  <div> 
    App
    <keep-alive>
       <component :is="currentComponent"></component>
    </keep-alive>
    <button @click="chengeView">切换视图</button>
  </div>
 </template>
<script>
import Home from './home'
import News from './news'
export default {
  name:"App",
  data(){
    return{
    //默认值显示Home
      currentComponent:Home ,
      //定一个默认值进行取反
      flag:false
    }
  },
  compinents:{
    Home,
    News 
  },
  methods:{
    chengeView(){
      if(this.flag){
        this.currentComponent = Home
        this.flag = false
      }else{
        this.currentComponent = News 
        this.flag = true
      }
    }
  }
}
</script>
<style>
</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值