vue中keep_alive使用

总结:keep-alive 是Vue的内置组件,能在组件切换过程中将状态保留在内存中,防止重复渲染DOM。结合vue-router中使用,可以缓存某个view的整个内容。

1.在App.vue中添加配置:

<!-- 缓存所有的页面 -->
<keep-alive>
<router-view v-if="$route.meta.keep_alive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keep_alive"></router-view>
 
2.在需要缓存的页面,配置路由
  {
      path: '/',
      name: 'headers',
      component: headers,
      meta:{
        keep_alive:true
      }
    },

3.使用,子组件header.vue

<template>
    <div>
      <h5>header</h5>
      <button @click="handclick"></button>
      <input type="text" v-model="msg">
     </div>
</template>
<script>
export default {
    name:"header",
  data(){
      return{
        msg:"",
      }
  },
  methods:{
      handclick(){
          let that=this;
          this.msg="里斯",
          setTimeout(function(){
              that.$router.push('/details')
          },2000);
          
      }
  }
}
</script>

<style>
button{
    height: 50px;
     50px;
    background-color: red;
}

</style>

4.父组件 detail.vue

<template>
<div>
  <h5>我是detail页面</h5>
  <keep-alive>
    <head></head>
  </keep-alive>
  <button @click="goheader">跳转会header界面</button>
</div>
</template>
<script>
import header from "./header.vue";
export default {
  components: {
    header
  },
  data() {
    return {};
  },
  methods: {
    goheader() {
      this.$router.push({ name: "headers" });
    }
  }
};
</script>

<style>
</style>

5.include/exclude两个属性 可以针对性缓存相应的组件

include - 字符串或正则表达式。只有名称匹配的组件会被缓存。

exclude - 字符串或正则表达式。任何名称匹配的组件都不会被缓存。

<keep-alive include="a,b">
  <component :is="view"></component>
</keep-alive>
<keep-alive :include="includedComponents">
  <router-view></router-view>
</keep-alive>
原文地址:https://www.cnblogs.com/huanhuan55/p/10108243.html