keep-alive内置组件 举个例子

<keep-alive> 是 Vue.js 内置的一个抽象组件,用于保留动态组件或者组件的状态,避免多次销毁和重新创建组件,以提高性能。下面是一个简单的例子:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Keep-Alive Example</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
</head>
<body>

<div id="app">
  <!-- 使用 keep-alive 包裹动态组件 -->
  <keep-alive>
    <component :is="currentComponent"></component>
  </keep-alive>

  <!-- 切换组件的按钮 -->
  <button @click="toggleComponent">Toggle Component</button>
</div>

<script>
// 创建两个组件
var ComponentA = {
  template: '<div>Component A</div>'
};

var ComponentB = {
  template: '<div>Component B</div>'
};

// 创建 Vue 实例
var app = new Vue({
  el: '#app',
  data: {
    currentComponent: 'ComponentA' // 初始化时显示 ComponentA 组件
  },
  methods: {
    toggleComponent: function() {
      // 切换组件
      this.currentComponent = this.currentComponent === 'ComponentA' ? 'ComponentB' : 'ComponentA';
    }
  },
  components: {
    ComponentA,
    ComponentB
  }
});
</script>

</body>
</html>

在这个例子中,我们与之前的动态组件例子类似,不同之处在于动态组件被 <keep-alive> 组件包裹起来。这样一来,当我们切换组件时,组件的状态将被保留,不会因为组件的销毁而丢失,当再次切换回来时,组件会保持之前的状态,从而提高了性能并提供更好的用户体验。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值