search
HomeWeb Front-endVue.jsHow to use VueRouter4.x? Quick start guide

How to use VueRouter4.x? Quick start guide

Jul 13, 2022 pm 08:11 PM
vuevue.jsvuerouter

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!

How to use VueRouter4.x? Quick start guide

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.

Hash history is useful for web applications without hosts (such as

file://), or when the configuration server cannot handle arbitrary URLs, but hashing is very poor for SEO;

History History is new in HTML5 and is not very friendly to IE, but Vue3 has given up on IE, so you don’t have to consider IE; this method is currently the most common method. But the application must be served over the http protocol.

Installation and usage process

First we install Vue Router, the command is as follows:

npm i vue-router

Then 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 and router-view

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 &#39;./components/root.vue&#39;
export default [
  {
    path: &#39;/&#39;,
    // 引入组件
    component: RootComponent
  },
  {
    path: &#39;/hello&#39;,
    // 路由懒加载引入组件
    component: () => import(&#39;./components/HelloWorld.vue&#39;)
  }
]

For other configuration items, you can refer to the documentation.

The code running results are as follows:

Routing lazy loadingHow to use VueRouter4.x? Quick start guide

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(&#39;./components/HelloWorld.vue&#39;)

Then the packaging (webpack, Vite) tool will package these dynamically imported components separately, as shown in the following figure:

Dynamic routingHow to use VueRouter4.x? Quick start guide

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: &amp;#39;/user/:id&amp;#39;, component: () =&gt; import(&amp;#39;@/components/User&amp;#39;) }</pre> Jump in the template as follows:

<router-link to="/user/10010"></router-link>

Or use the

push

method provided by

useRouter

For example: <pre class='brush:php;toolbar:false;'>import { useRouter } from &amp;#39;vue-router&amp;#39; const {push} = useRouter() push({ path: &amp;#39;/user&amp;#39;, params: { id: 10010 } }) // 或者 let id = 10010 push(&amp;#39;/user/&amp;#39; + id)</pre> You can obtain the routing address through the useRoute hook. The usage is consistent with

useRouter

. Match all routes

VueRouter’s dynamic routing allows us to match routes that are not matched. The sample code is as follows:
{
  path: &#39;/:pathMatch(.*)&#39;,
  component: () => import(&#39;./components/Page404.vue&#39;),
},
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(&#39;./components/HelloWorld.vue&#39;),
  children: [
    {
      path: 'about',
      component: () => import('./components/about.vue'),
    },
    {
      path: 'user',
      component: () => import('./components/user.vue'),
    },
  ],
},

子组件比较简单,只有一个<h1></h1>标签,最终效果如下:

How to use VueRouter4.x? Quick start guide

写在最后

这篇文章到这就结束了,总的来说比较简单没有什么太深入的东西,比较适合入门。

【相关视频教程推荐:vuejs入门教程web前端入门

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!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Understanding Vue.js: Primarily a Frontend FrameworkUnderstanding Vue.js: Primarily a Frontend FrameworkApr 17, 2025 am 12:20 AM

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix's Frontend: Examples and Applications of React (or Vue)Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AM

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

The Frontend Landscape: How Netflix Approached its ChoicesThe Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AM

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

React vs. Vue: Which Framework Does Netflix Use?React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

The Choice of Frameworks: What Drives Netflix's Decisions?The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AM

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

Vue.js in the Frontend: Real-World Applications and ExamplesVue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AM

Vue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.

Vue.js and React: Understanding the Key DifferencesVue.js and React: Understanding the Key DifferencesApr 10, 2025 am 09:26 AM

Vue.js is suitable for small to medium-sized projects, while React is more suitable for large and complex applications. 1. Vue.js' responsive system automatically updates the DOM through dependency tracking, making it easy to manage data changes. 2.React adopts a one-way data flow, and data flows from the parent component to the child component, providing a clear data flow and an easy-to-debug structure.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

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.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools