vue3的 keep-alive 使用,以及activated鉤子 和 vue-router中的 scrollBehavior的使用

先上代碼

<router-view v-slot="{ Component }">
  <keep-alive>
    <component :key="$route.name" :is="Component" v-if="$route.meta.keepAlive" />
  </keep-alive>
  <component :key="$route.name" :is="Component" v-if="!$route.meta.keepAlive" />
</router-view>
const routes = [
  {
    path: '/',
    redirect: '/home',
  },
  // Home
  {
    path: '/home',
    name: 'Home',
    meta: {
      keepAlive: true,
    },
    component: Home
  },
  // Detail
  {
    path: '/detail',
    name: 'Detail',
    meta: {
      keepAlive: false,
    },
    component: () => import('@/views/detail/index.vue'),
  },
  ...
]
const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

 


vue2的keep-alive 參考

<keep-alive include="Home,Ranking">
  <router-view />
</keep-alive>

 


vue3 使用注意點:

報錯:parentComponent.ctx.deactivate is not a function :

需要在 中的 增加唯一key,比如 <component :key="$route.name" ... />


 


keep-alive相關的鉤子函數: activated / deactivated

https://v3.cn.vuejs.org/api/options-lifecycle-hooks.html#activated

onActivated(() => {

})
onDeactivated(() => {

})

 


vue3中 vue-router 的scrollBehavior變化

https://router.vuejs.org/zh/guide/advanced/scroll-behavior.html

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (to.name === 'Detail') {
      return { x: 0, y: 0 };
    }
    return savedPosition;
  }
});

改爲:

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (to.name === 'Detail') {
      return { top: 0 };
    }
    return savedPosition;
  }
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章