简体   繁体   中英

keep-alive not works in vue.js

My vuejs version is 3. I implement both of these ways to use keep-alive in my app.

1

<template>
  <div id="nav" classs="container is-max-desktop"></div>
<keep-alive>
  <router-view />
</keep-alive>
</template>

<style>
@import "~bulma/css/bulma.css";
</style>

2

import { createRouter, createWebHistory } from "vue-router";
import Index from "../views/Index.vue";
import Create from "../views/Create.vue";
import Edit from "../views/Edit.vue";

const routes = [
  {
    name: "Index",
    path: "/",
    component: Index,
    meta: { KeepAlive: true },
  },
  {
    name: "Edit",
    path: "/edit/:id",
    component: Edit,
    meta: { KeepAlive: true },
  },
  {
    name: "Create",
    path: "/create",
    component: Create,
    meta: { KeepAlive: true },
  },
  {
    path: "/about",
    name: "About",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/About.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

export default router;

Simply, I apply many filters on my page but when I came back to that page they are gone. Help me to solve this problem. Thank you.

Keep alive caches components when dynamically switching them which will retain the data's in that particular component while switching. Use the below code for integration,

Maincomponent.vue

<script>
import Component1 from './Component1.vue'
import Component2 from './Component2.vue'
  
export default {
  components: { Component1, Component2 },
  data() {
    return {
      current: 'Component1'
    }
  }
}
</script>

<template>
  <div class="demo">
    <label><input type="radio" v-model="current" value="Component1" /> A</label>
    <label><input type="radio" v-model="current" value="Component2" /> B</label>
    <KeepAlive>
      <component :is="current"></component>
    </KeepAlive>
  </div>
</template>

Component1.vue

<script>
export default {
  data() {
    return {
      count: 0
    }
  }
}
</script>

<template>
  <div>
    <p>Current component: A</p>
    <span>count: {{ count }}</span>
    <button @click="count++">+</button>
  </div>
</template>

Component2.vue

<script>
export default {
  data() {
    return {
      msg: ''
    }
  }
}
</script>


<template>
  <div>
    <p>Current component: B</p>
    <span>Message is: {{ msg }}</span>
    <input v-model="msg">
  </div>
</template>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM