search
HomeWeb Front-endVue.js[Compilation and sharing] Some vue-router related interview questions (with answer analysis)

This article will summarize and share with you some vue-router related interview questions (with answer analysis), help you sort out the basic knowledge, and enhance the vue-router knowledge reserve. It is worth collecting, come and take a look!

[Compilation and sharing] Some vue-router related interview questions (with answer analysis)

The principle of vue-router

In a single-page application, switching between different components needs to be implemented through front-end routing .

Front-end routing

1.key is the path, value is the component, used to display the page content
2. Working process: when the browser's path changes , the corresponding component will be displayed.
vue-router’s routing function: Map components to routes and then render them

Mainly

The hash pattern of the route

  • hash is the ## in the URL ## and the following part, the URL after # will not be sent to the server, so changing the hash part in the URL will not cause the page to refresh

  • Window can monitor

    onhashchange event changes. When the hash changes, read the content after #, match routing rules based on the information, and change the page routing by changing window.location.hash.

Three ways to change the URL

    Change the URL through the browser forward and backward
  • Change the URL through tags
  • Change the URL through window.location

Advantages

    Only the front-end needs to configure the routing table, no back-end participation is required
  • Good compatibility, all browsers can support it
  • Changes in the hash value will not send requests to the backend, it is completely front-end routing

##Disadvantages

The hash value needs to be preceded by #, which does not comply with the url specification and is not beautiful

routing history mode - using the new pushState() and replaceState()## in the history interface of H5's history API

  • #html5 # Method, used to add and modify records in the browsing history, change the page path, so that the URL jump will not reload the page.

    The
  • popstate
  • event is similar to the

    hashchange event, but the popstate event is somewhat different: Only when making the browser popState will be called only when behavior is triggered. It will be triggered when the user clicks the browser's back button and forward button, or uses JavaScript to call the History.back(), History.forward(), and History.go() methods.

  • Advantages

Conforms to URL address specifications, no # is required, and it is more beautiful to use
  • Disadvantages

When the user

manually enters the address or refreshes the page, a url request
    will be initiated, and the backend needs to configure the index.html page The user cannot match the static resource, otherwise a 404 error will occur.
  • The compatibility is relatively poor, and the new pushState()
  • and
  • replaceState( are used in the HTML5 History object. ) method requires the support of a specific browser.

What is the difference between $route and $router? $router is an instance object of VueRouter, representing the only router object for the entire application. Contains routing jump methods, hook functions, etc. $route is the current routing object, which represents the routing rules of this component. Each route will have a route object, which is a local object.


Vue-router parameters are passed in several ways, what are the differences?

-DescriptionHow to specify the jump routeIf no parameters are passedCan parameters be passed without the required valueparams parameterparams is part of the route , If placeholders are configured, query parametersquery will not

Vue-router parameter loss problem

When the params parameter is passed, the parameters received by the setting placeholder are passed, and the address bar will not be displayed and Refresh will be lost.

Solution: You can get the parameters and save them locally through this.$route.params

vue-router has several hooks function? What exactly is it and what is the execution process?

vue-router The navigation guard provided is mainly used to guard navigation by jumping or canceling.

  • Global routing guards: There can be multiple calls based on the order of creation.
    • router.beforeEach() Global front guard, will be triggered every time you navigate .
    • router.afterEach() Global post route guard, after each route jump is completed. Next function will not be accepted, the jump has been completed and has entered the component
    • router.beforResolve() Global parsing guard, before routing jump, all In-component guards and Asynchronous routing components are triggered after being parsed, and they will also be triggered every time they navigate. After the parsing is completed, the navigation is determined and ready to jump.
  • Route guard within the component
    • beforeRouteEnter() is called before the route enters the component. This hook is between beforeEach and beforeEnter After.
      You have not entered the component yet, and the component instance has not been created yet. Therefore, the component instance cannot be obtained. At this time, this is undefined and is triggered before the beforeCreate life cycle.
    • beforeRouteUpdate() this is already available, so there is no need to pass a callback to next. For a path /foo/:id with dynamic parameters, when jumping between /foo/1 and /foo/2, since the unified Foo component will be rendered, this component instance will be reused. This hook can be called in this case.
    • beforeRouteLeave()Called when leaving the component, this is already available, so there is no need to pass a callback to next.
  • Exclusive routing guard
    • beforeEnter() You need to define the beforeEnter guard on the routing configuration, this The guard is only triggered when entering the route, executed immediately after beforeEach, and will not be triggered when params, query or hash change.
The order of calls before entering the component

beforeEach()=>beforeEnter()=>beforeRouteEnter()=>beforeResolve() This The process cannot use this because the component instance has not been created yet, so you need to use the next function

Complete navigation parsing process 1. Navigation is triggered.
2. Call the
beforeRouteLeave guard in the deactivated component. 3. Call the global
beforeEach guard. 4. Call the
beforeRouteUpdate guard in the reused component. 5. Call
beforeEnter in the routing configuration. 6. Parse asynchronous routing components.
7. Call
beforeRouteEnter in the activated component. 8. Call the global
beforeResolve guard. 9. Navigation is confirmed.
10. Call the global afterEach hook.
11. Trigger DOM update.
12. Call
beforeRouteEnter and pass to the next callback function in the guard. The created component instance will be passed in as a parameter of the callback function.

[Compilation and sharing] Some vue-router related interview questions (with answer analysis)

keep-alive

keep-alive can implement component caching, The current component will not be uninstalled when the component is switched.

keep-aliveThe tag mainly has three attributes: include, exclude, and max

  • include, exclude The first two attributes allow keep-alive conditional caching
  • max You can define the maximum number of cached components. If this number is exceeded, Before the next new instance is created, the instance in the cache component that has not been accessed for the longest time will be destroyed.
Two life cycles

activated/deactivated, used to know whether the current component is active.

Keep-alive principle cache management special mount/unmount process

Special uninstall/mount process:

activated/deactivated Cache management:
LRU (Least Recently Used) Least Recently Used is an elimination algorithm

Special uninstall/mount process Since it cannot be The component is truly uninstalled, so keep-alive moves the component from the original container to another fake container to achieve fake uninstallation. When mounting, it is moved from the hidden container to the original container. Corresponding to the component's
activated and deactivated life cycle keepAlive will mark internal components (that need to be cached)

  • Add the shouldKeepAlive attribute on the vnode object of the internal component to tell the renderer that when the component is unloaded, the component needs to be cached and not actually uninstalled
  • Add keptAlive on the vnode object of the internal component Attribute, if the component has been cached, add a mark to indicate that the renderer will not be remounted and can be activated directly.

[Compilation and sharing] Some vue-router related interview questions (with answer analysis)

Cache strategy: Recently used at least

Use Map object cache to cache components. The key is the vnode.type value, and the value is the vnode object, because there is a reference to the component instance (vnode.component)

in the vnode object of the component.
  • cache The former is used to store the virtual dom collection of cache components
  • keys The latter is used to store the key collection of cache components
  • Generate a cache key based on the component ID and tag, and check whether the component instance has been cached in the cache object. If it exists, directly retrieve the cached value and update the key's position in keys (updating the key's position is the key to implementing the LRU replacement strategy).

  • If it does not exist, store the component instance in the map object and save the key value. Then check whether the number of cached instances exceeds the max setting value. If it exceeds the max setting value, delete the most recent one according to the LRU replacement policy. The longest unused instance (that is, the key with index 0).

(Learning video sharing: vuejs introductory tutorial, Basic programming video)

Path/params parameter You must use name to specify the routeIf this route has params parameters, but this parameter is not passed during the jump, the jump will fail or the page will have no content.
Placeholders that are not included in the delivery path will not be displayed on the address bar and will be lost upon refresh
Path? key1=val1 & key2=val2.... 1. You can use name to specify the route 2. You can use path to specify the route query It is a parameter spliced ​​after the url. It doesn’t matter if it is not available.

The above is the detailed content of [Compilation and sharing] Some vue-router related interview questions (with answer analysis). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
Vue.js vs. React: Scalability and MaintainabilityVue.js vs. React: Scalability and MaintainabilityMay 10, 2025 am 12:24 AM

Vue.js and React each have their own advantages in scalability and maintainability. 1) Vue.js is easy to use and is suitable for small projects. The Composition API improves the maintainability of large projects. 2) React is suitable for large and complex projects, with Hooks and virtual DOM improving performance and maintainability, but the learning curve is steeper.

The Future of Vue.js and React: Trends and PredictionsThe Future of Vue.js and React: Trends and PredictionsMay 09, 2025 am 12:12 AM

The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

Netflix's Frontend: A Deep Dive into Its Technology StackNetflix's Frontend: A Deep Dive into Its Technology StackMay 08, 2025 am 12:11 AM

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js and the Frontend: Building Interactive User InterfacesVue.js and the Frontend: Building Interactive User InterfacesMay 06, 2025 am 12:02 AM

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

What are the disadvantages of VueJs?What are the disadvantages of VueJs?May 05, 2025 am 12:06 AM

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix: Unveiling Its Frontend FrameworksNetflix: Unveiling Its Frontend FrameworksMay 04, 2025 am 12:16 AM

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

Frontend Development with Vue.js: Advantages and TechniquesFrontend Development with Vue.js: Advantages and TechniquesMay 03, 2025 am 12:02 AM

Reasons for Vue.js' popularity include simplicity and easy learning, flexibility and high performance. 1) Its progressive framework design is suitable for beginners to learn step by step. 2) Component-based development improves code maintainability and team collaboration efficiency. 3) Responsive systems and virtual DOM improve rendering performance.

Vue.js vs. React: Ease of Use and Learning CurveVue.js vs. React: Ease of Use and Learning CurveMay 02, 2025 am 12:13 AM

Vue.js is easier to use and has a smooth learning curve, which is suitable for beginners; React has a steeper learning curve, but has strong flexibility, which is suitable for experienced developers. 1.Vue.js is easy to get started with through simple data binding and progressive design. 2.React requires understanding of virtual DOM and JSX, but provides higher flexibility and performance advantages.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!