如何使某些组件“保持活动状态"在 Vue 3 中使用路由器视图? [英] How to make certain component "keep-alive" with router-view in Vue 3?

查看:43
本文介绍了如何使某些组件“保持活动状态"在 Vue 3 中使用路由器视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个包含两个主要组件的小应用程序,我使用 vue 路由器在组件之间进行路由.

I've created a small app that consists of two main components and I am using vue router to route between components.

第一个组件称为 MoviesList,第二个组件称为 Movie.我已经在路由 js 文件中注册了它们.

First component is called MoviesList and the second one is called Movie. I've registered them in routes js file.

const routes = [
  {
    path: '/',
    name: 'Home',
    component: MoviesList
  },

  {
    path: '/:movieId',
    name: 'Movie',
    component: Movie
  }
  
]

我的 App.vue 模板是这样的

And my App.vue template looks like this

<template>
   <router-view></router-view>
</template>

我怎样才能缓存 MovieList 组件,或者说它被 <keep-alive> 标签包裹?期望的结果是缓存 MovieList 组件,而不缓存 Movie 组件.

How can I make MovieList component cached or so to say like it is wrapped with <keep-alive> tags? Desired outcome would be to make MovieList component cached and Movie component not.

我想这样做是因为 MovieList 组件有一个在 mount() 钩子上运行的方法,每当我切换路由并返回时,该方法再次运行,因为组件被重新渲染.

I want to do that because MovieList component has a method that runs on mounted() hook and whenever I switch routes and come back that method runs again because component is re-rendered.

推荐答案

试试这个include=MoviesList",或者exclude=Movie"也行

<router-view v-slot="{ Component }">
  <keep-alive include="MoviesList">
    <component :is="Component" />
  </keep-alive>
</router-view>

这篇关于如何使某些组件“保持活动状态"在 Vue 3 中使用路由器视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆