keep-alive的用法及作用

本文通过一个Vue实例展示了`keep-alive`组件的使用,说明了它如何缓存子组件状态,避免重复渲染。在父组件中,对比了有无`keep-alive`包裹时子组件的切换效果,详细解释了`keep-alive`在维护组件活性和优化性能方面的作用。子组件包括展示博客内容的部分,`keep-alive`使得在不同博客间切换时保持了先前的选择状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

keep-alive的用法及作用

//这是父组件代码
<template>
  <div id="dynamic-component-demo">
    <h4>可以点击按钮查看效果</h4>
    <button
      v-for="tab in tabs"
      v-bind:key="tab"
      v-bind:class="['tab-button', { active: currentTab === tab }]"
      v-on:click="currentTab = tab">
      {{ tab }}
    </button>

    <h4>keep-alive可以将失活的组件缓存起来</h4>
    <keep-alive>
      <component v-bind:is="currentTabComponent" class="tab"></component>
    </keep-alive>

    <h4>没有keep-alive包裹则不会缓存</h4>
    <component v-bind:is="currentTabComponent" class="tab"></component>
  </div>
</template>

<script>
//引入子组件
  import UseKeepAliveOne from './UseKeepAliveOne'
  import UseKeepAliveTwo from './UseKeepAliveTwo'

  export default {
    name: "HomeKeepalive",
    //注册子组件
    components: {
      UseKeepAliveOne,
      UseKeepAliveTwo
    },
    data() {
      return {
        currentTab: "One",
        tabs: ["One", "Two"]
      }
    },
    computed: {
      currentTabComponent: function() {
        return "use-keep-alive-" + this.currentTab.toLowerCase();
      }
    },
    methods: {}
  }
</script>

<style scoped>
  .tab-button {
    padding: 6px 10px;
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
    border: 1px solid #ccc;
    cursor: pointer;
    background: #f0f0f0;
  }

  .tab-button:hover {
    background: #e0e0e0;
  }

  .tab-button.active {
    background: #e0e0e0;
  }

  .tab {
    border: 1px solid #ccc;
    padding: 10px;
  }
</style>

//这是子组件1的代码
<template>
  <div class="posts-tab">
    <ul class="posts-sidebar">
      <li
        v-for="post in posts"
        v-bind:key="post.id"
        v-bind:class="{ selected: post === selectedPost }"
        v-on:click="selectedPost = post">
        {{ post.title }}
      </li>
    </ul>
    <div class="selected-post-container">
      <div v-if="selectedPost" class="selected-post">
        <h3>{{ selectedPost.title }}</h3>
        <div v-html="selectedPost.content"></div>
      </div>
      <strong v-else>
        Click on a blog title to the left to view it.
      </strong>
    </div>
  </div>
</template>

<script>
  export default {
    name: "UseKeepalive",
    data() {
      return {
        posts: [
          {
            id: 1,
            title: "First",
            content:
              "<p>Dont wait for the storm to pass, dance in the rain kick up litter decide to want nothing to do with my owner today demand to be let outside at once, and expect owner to wait for me as i think about it cat cat moo moo lick ears lick paws so make meme, make cute face but lick the other cats. Kitty poochy chase imaginary bugs, but stand in front of the computer screen. Sweet beast cat dog hate mouse eat string barf pillow no baths hate everything stare at guinea pigs. My left donut is missing, as is my right loved it, hated it, loved it, hated it scoot butt on the rug cat not kitten around</p>"
          },
          {
            id: 2,
            title: "Second",
            content:
              "<p>Bushwick blue bottle scenester helvetica ugh, meh four loko. Put a bird on it lumbersexual franzen shabby chic, street art knausgaard trust fund shaman scenester live-edge mixtape taxidermy viral yuccie succulents. Keytar poke bicycle rights, crucifix street art neutra air plant PBR&B hoodie plaid venmo. Tilde swag art party fanny pack vinyl letterpress venmo jean shorts offal mumblecore. Vice blog gentrify mlkshk tattooed occupy snackwave, hoodie craft beer next level migas 8-bit chartreuse. Trust fund food truck drinking vinegar gochujang.</p>"
          },
          {
            id: 3,
            title: "Third",
            content:
              "<p>Icing dessert soufflé lollipop chocolate bar sweet tart cake chupa chups. Soufflé marzipan jelly beans croissant toffee marzipan cupcake icing fruitcake. Muffin cake pudding soufflé wafer jelly bear claw sesame snaps marshmallow. Marzipan soufflé croissant lemon drops gingerbread sugar plum lemon drops apple pie gummies. Sweet roll donut oat cake toffee cake. Liquorice candy macaroon toffee cookie marzipan.</p>"
          }
        ],
        selectedPost: null
      }
    },
    methods: {}
  }
</script>

<style scoped>
  .posts-sidebar {
    max-width: 40vw;
    margin: 0;
    padding: 0 10px 0 0;
    list-style-type: none;
    border-right: 1px solid #ccc;
  }

  .posts-sidebar li {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    cursor: pointer;
  }

  .posts-sidebar li:hover {
    background: #eee;
  }

  .posts-sidebar li.selected {
    background: lightblue;
  }

  .selected-post-container {
    padding-left: 10px;
  }

  .selected-post > :first-child {
    margin-top: 0;
    padding-top: 0;
  }
</style>

//这是子组件2的代码
<template>
  <div>Two component</div>
</template>

<script>
  export default {
    name: "UseKeepAliveTwo",
    data() {
      return {}
    },
    methods: {}
  }
</script>

<style scoped>

</style>

有不对的地方还请指出,谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值