How to use VueRouter4.x? The following article will share with you a quick tutorial and introduce how to quickly get started with VueRouter4.x in 10 minutes. I hope it will be helpful to everyone!
Vue Router is a routing plug-in developed by the Vue team that is deeply integrated with the core of Vue.js, making it very simple to build single-page programs with Vue; The latest version of Vue Router is 4.X, which is also the recommended version for Vue3. In this article, we will learn about Vue Router 4.X. (Learning video sharing: vue video tutorial)
URL.hash and History
There are two types of history## in Vue Router # (Record historical routing), respectively
URL.hash and
History provided in HTML5.
file://), or when the configuration server cannot handle arbitrary URLs, but hashing is very poor for SEO;
Installation and usage process
First we install Vue Router, the command is as follows:npm i vue-routerThen in
main.js Write the following code:
import { createApp } from 'vue' import App from './App.vue' // 1 引入 createRouter import { createRouter, createWebHistory } from 'vue-router' // 2 定义路由映射表 const routes = [ /* more router */ ] // 3 创建路由实例,并传递对应配置 const router = createRouter({ // history 模式 这里使用createWebHistory history: createWebHistory(), // 传递路由映射表 routes }) createApp(App).use(router).mount('#app')If there are too many
routes in the above code, you can define a
router.js file and extract it, sample code As follows:
router.js
export default [ /* more router */ ]
main.js
import { createApp } from 'vue' import App from './App.vue' // 2 引入路由映射表 import routes from './router' // 1 引入 createRouter import { createRouter, createWebHistory } from 'vue-router' // 3 创建路由实例,并传递对应配置 const router = createRouter({ // history 模式 这里使用createWebHistory history: createWebHistory(), // 传递路由映射表 routes }) createApp(App).use(router).mount('#app')or **directly in ****# Directly export a routing instance in ##router.js
and use it in main.js**
( This method is more commonly used).
router-link
##
is a custom component provided by Vue, used to create links. The native is not used in Vue, because
will be reset after changing the URL. Loading the page but
will not; for details about which properties the
component supports, please refer to the
documentation.
router-view
## component is used for the component corresponding to the URL, such as the following code:
<template> <router-link to="/hello" ><img src="/static/imghwm/default1.png" data-src="./assets/logo.png" class="lazy" alt="Vue logo" /></router-link> <router-view></router-view> </template>
Then our router.js
code is as follows:
import RootComponent from './components/root.vue' export default [ { path: '/', // 引入组件 component: RootComponent }, { path: '/hello', // 路由懒加载引入组件 component: () => import('./components/HelloWorld.vue') } ]
For other configuration items, you can refer to the documentation
.
The code running results are as follows:
Routing lazy loading
When our application becomes more and more When the JavaScript code is large, the packaged JavaScript code will also be particularly large. At this time, we need to split the entire application into different blocks, and Vue Router supports this function. We only need toreplace the static import with dynamic import. , such as the above code:
component: () => import('./components/HelloWorld.vue')
Then the packaging (webpack, Vite) tool will package these dynamically imported components separately, as shown in the following figure:
Dynamic routing
VueRouter allows us to dynamically set routing matching rules. For example, we now have a User component, and the content of the component will Different content is displayed according to different IDs. The setting method only needs to be set in the form of
:parameter name. For example:
<pre class='brush:php;toolbar:false;'>{
path: &#39;/user/:id&#39;,
component: () => import(&#39;@/components/User&#39;)
}</pre>
Jump in the template as follows:
<router-link to="/user/10010"></router-link>
Or use the
pushmethod provided by
useRouter For example: <pre class='brush:php;toolbar:false;'>import { useRouter } from &#39;vue-router&#39;
const {push} = useRouter()
push({
path: &#39;/user&#39;,
params: { id: 10010 }
})
// 或者
let id = 10010
push(&#39;/user/&#39; + id)</pre>
You can obtain the routing address through the useRoute
hook. The usage is consistent with
. Match all routes
VueRouter’s dynamic routing allows us to match routes that are not matched. The sample code is as follows: {
path: '/:pathMatch(.*)',
component: () => import('./components/Page404.vue'),
},
The current route If the match is unsuccessful, this route will be matched.
Routing nesting
Now we have a requirement, which is to store two components under the HelloWorld component and need to switch between the two components.
这个时候路由嵌套的就发挥作用了,其实路由嵌套比较简单,就是通过路由配置中的一个children
属性来实现,示例代码如下:
HelloWorld.vue
<template> <h1 id="Hello-nbsp-World">Hello World</h1> <div style=" display: flex; justify-content: space-between; width: 240px; margin: 0 auto; " > <router-link to="about">about</router-link> <router-link to="user">user</router-link> </div> <router-view></router-view> </template>
router.js
{ path: '/hello', // 路由懒加载引入组件 component: () => import('./components/HelloWorld.vue'), children: [ { path: 'about', component: () => import('./components/about.vue'), }, { path: 'user', component: () => import('./components/user.vue'), }, ], },
子组件比较简单,只有一个<h1></h1>
标签,最终效果如下:
写在最后
这篇文章到这就结束了,总的来说比较简单没有什么太深入的东西,比较适合入门。
The above is the detailed content of How to use VueRouter4.x? Quick start guide. For more information, please follow other related articles on the PHP Chinese website!

Vue.js is suitable for fast development and small projects, while React is more suitable for large and complex projects. 1.Vue.js is simple and easy to learn, suitable for rapid development and small projects. 2.React is powerful and suitable for large and complex projects. 3. The progressive features of Vue.js are suitable for gradually introducing functions. 4. React's componentized and virtual DOM performs well when dealing with complex UI and data-intensive applications.

Vue.js and React each have their own advantages and disadvantages. When choosing, you need to comprehensively consider team skills, project size and performance requirements. 1) Vue.js is suitable for fast development and small projects, with a low learning curve, but deep nested objects can cause performance problems. 2) React is suitable for large and complex applications, with a rich ecosystem, but frequent updates may lead to performance bottlenecks.

Vue.js is suitable for small to medium-sized projects, while React is suitable for large projects and complex application scenarios. 1) Vue.js is easy to use and is suitable for rapid prototyping and small applications. 2) React has more advantages in handling complex state management and performance optimization, and is suitable for large projects.

Vue.js and React each have their own advantages: Vue.js is suitable for small applications and rapid development, while React is suitable for large applications and complex state management. 1.Vue.js realizes automatic update through a responsive system, suitable for small applications. 2.React uses virtual DOM and diff algorithms, which are suitable for large and complex applications. When selecting a framework, you need to consider project requirements and team technology stack.

Vue.js and React each have their own advantages, and the choice should be based on project requirements and team technology stack. 1. Vue.js is community-friendly, providing rich learning resources, and the ecosystem includes official tools such as VueRouter, which are supported by the official team and the community. 2. The React community is biased towards enterprise applications, with a strong ecosystem, and supports provided by Facebook and its community, and has frequent updates.

Netflix uses React to enhance user experience. 1) React's componentized features help Netflix split complex UI into manageable modules. 2) Virtual DOM optimizes UI updates and improves performance. 3) Combining Redux and GraphQL, Netflix efficiently manages application status and data flow.

Vue.js is a front-end framework, and the back-end framework is used to handle server-side logic. 1) Vue.js focuses on building user interfaces and simplifies development through componentized and responsive data binding. 2) Back-end frameworks such as Express and Django handle HTTP requests, database operations and business logic, and run on the server.

Vue.js is closely integrated with the front-end technology stack to improve development efficiency and user experience. 1) Construction tools: Integrate with Webpack and Rollup to achieve modular development. 2) State management: Integrate with Vuex to manage complex application status. 3) Routing: Integrate with VueRouter to realize single-page application routing. 4) CSS preprocessor: supports Sass and Less to improve style development efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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

SublimeText3 Chinese version
Chinese version, very easy to use

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
