Skip to content

Conversation

@mynetfan
Copy link
Collaborator

@mynetfan mynetfan commented Mar 10, 2025

Description

在开启keep-alive的情况下:
自动调整路由的component名称与路由同步,解决不同路由使用同一个组件作为页面内容时的缓存问题;

合并此PR之后,无需因为keep-alive的原因为页面组件显式设置name

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update
  • Please, don't make changes to pnpm-lock.yaml unless you introduce a new test example.

Checklist

ℹ️ Check all checkboxes - this will indicate that you have done everything in accordance with the rules in CONTRIBUTING.

  • If you introduce new functionality, document it. You can run documentation with pnpm run docs:dev command.
  • Run the tests with pnpm test.
  • Changes in changelog are generated from PR name. Please, make sure that it explains your changes in an understandable manner. Please, prefix changeset messages with feat:, fix:, perf:, docs:, or chore:.
  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules

Summary by CodeRabbit

  • New Features
    • Enhanced application routing to provide improved caching support for lazy-loaded views. With dynamic management of component display based on caching conditions, users can expect smoother navigation and improved performance. These updates result in more efficient transitions between views, ultimately contributing to a more responsive and seamless experience. Overall, this release improves user interaction across dynamic views.

@changeset-bot
Copy link

changeset-bot bot commented Mar 10, 2025

⚠️ No Changeset found

Latest commit: e07d87b

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 10, 2025

Walkthrough

The changes enhance the generateRoutes function in the accessible.ts file by introducing logic to modify the component of routes that have the keepAlive meta property. If a route's meta.keepAlive is true, and both the component and name properties are valid, the component is wrapped in a new definition using defineComponent. This allows for conditional caching when using keep-alive, facilitating better management of lazy-loaded components.

Changes

File Change Summary
packages/effects/access/src/accessible.ts Enhanced generateRoutes to check for keepAlive routes; if valid, wraps the component in an async defineComponent that lazy-loads and renders the original component with proper validations using isFunction and isString.

Sequence Diagram(s)

sequenceDiagram
    participant GR as generateRoutes
    participant UT as Utility Functions
    participant AW as Async Wrapper
    participant OC as Original Component

    GR->>GR: Process each route
    GR->>UT: Validate (isFunction(component) & isString(name))
    UT-->>GR: Return validation results
    alt Route has `meta.keepAlive` and valid properties
        GR->>AW: Wrap component with async wrapper (defineComponent)
        AW->>OC: Asynchronously import original component
        AW-->>GR: Return wrapped component with caching support
    else
        GR-->>GR: Retain original component without wrapping
    end
Loading

Possibly related PRs

Suggested labels

feature

Suggested reviewers

  • anncwb
  • vince292007

Poem

In the code garden, I hop with glee,
A rabbit spice in routes set free.
Lazy loads, keep-alive so bright,
Wrapped and cached with pure delight.
Hopping on changes—code carrots in sight!
🐇✨
Cheers to a swift route flight!

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

Scope: all 5 workspace projects
 ERR_PNPM_OPTIONAL_DEPS_REQUIRE_PROD_DEPS  Optional dependencies cannot be installed without production dependencies


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c0c11a4 and e07d87b.

📒 Files selected for processing (1)
  • packages/effects/access/src/accessible.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/effects/access/src/accessible.ts
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Test (windows-latest)
  • GitHub Check: Lint (windows-latest)
  • GitHub Check: Check (windows-latest)
  • GitHub Check: post-update (windows-latest)
  • GitHub Check: post-update (ubuntu-latest)
  • GitHub Check: Check (ubuntu-latest)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/effects/access/src/accessible.ts (1)

93-111:

❓ Verification inconclusive

Watch for naming collisions and consider caching.

  1. Naming collisions: When wrapping the component under route.name, if multiple routes share the same name, you might encounter collisions in <keep-alive> usage. Ensure route names are unique if keep-alive caching is expected to differentiate components.

  2. Optional caching: For performance gains, consider storing the resolved component to avoid subsequent re-fetching on repeated navigations. For example:

 route.component = async () => {
+  if (originalComponent._cached) {
+    return originalComponent._cached;
+  }

   const { default: component } = await originalComponent();
   const wrapped = defineComponent({
     name: route.name as string,
     setup(props, { attrs, slots }) {
       return () => h(component, { ...props, ...attrs }, slots);
     },
   });

+  originalComponent._cached = wrapped;
   return wrapped;
 };

Below is a script to scan for duplicate route names across the codebase, helping ensure keep-alive logic behaves as intended:


🏁 Script executed:

#!/bin/bash
# Description: Find potential duplicate route names in .ts or .js files.

fd -e ts -e js --exec rg -A 2 "name:\s*['\"]" {}

Length of output: 39393


Action Required: Verify Route Name Uniqueness and Consider Caching Optimization

Please ensure that the keep-alive logic works as intended:

  • Naming Collisions:
    The wrapping logic uses route.name when defining the component. Our scan indicates that many route definitions (e.g., names like "Home", "About", "Affix") appear multiple times in the codebase. Duplicate names may cause unwanted collisions in <keep-alive>. Please manually verify that routes intended for caching have unique names.

  • Optional Caching:
    To avoid repeated fetching and improve performance, consider caching the wrapped component after its first resolution. For example:

     route.component = async () => {
    +  if (originalComponent._cached) {
    +    return originalComponent._cached;
    +  }
    
       const { default: component } = await originalComponent();
       const wrapped = defineComponent({
         name: route.name as string,
         setup(props, { attrs, slots }) {
           return () => h(component, { ...props, ...attrs }, slots);
         },
       });
    
    +  originalComponent._cached = wrapped;
       return wrapped;
     };

Please review the potential duplicate route names (especially in areas related to keep-alive usage) and confirm that they are either intentional or need to be adjusted.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 096545c and c0c11a4.

📒 Files selected for processing (1)
  • packages/effects/access/src/accessible.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Test (windows-latest)
  • GitHub Check: Lint (windows-latest)
  • GitHub Check: Check (windows-latest)
  • GitHub Check: post-update (windows-latest)
  • GitHub Check: Lint (ubuntu-latest)
  • GitHub Check: post-update (ubuntu-latest)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Check (ubuntu-latest)
🔇 Additional comments (4)
packages/effects/access/src/accessible.ts (4)

1-1: Imports look correct.
No issues identified with importing RouteComponent from vue-router.


9-9: Correct usage of defineComponent and h from Vue.
These imports are relevant for dynamically wrapping components in the subsequent code.


16-17: Utility imports are appropriate.
The usage of isFunction and isString to safeguard route validation logic is a good practice.


90-90: Doc comment alignment looks fine.
No issues found in the updated commentary for clarifying the behavior of lazy-loaded components.

@mynetfan mynetfan merged commit 17e2a02 into vbenjs:main Mar 10, 2025
14 checks passed
@mynetfan mynetfan deleted the fix/keep-alive branch March 10, 2025 08:25
2yllll pushed a commit to 2yllll/vue-vben-admin that referenced this pull request Mar 17, 2025
* fix: auto set component name for keep-alive

* fix: type define
@github-actions github-actions bot locked and limited conversation to collaborators Apr 10, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant