Home Web Front-end JS Tutorial Detailed explanation of vue-router routing and navigation between pages

Detailed explanation of vue-router routing and navigation between pages

Dec 23, 2017 am 11:26 AM
vue-router navigation page

vue-router is the official routing plug-in of Vue.js. It is deeply integrated with vue.js and is suitable for building single-page applications. Vue's single-page application is based on routing and components. Routing is used to set access paths and map paths and components. Traditional page applications use some hyperlinks to achieve page switching and jumps. In the vue-router single-page application, it is switching between paths, that is, switching of components.

vue-router

We know that routing defines a series of access address rules, and the routing engine finds the corresponding processing page based on these rule matches. , and then forwards the request to the page for processing. It can be said that all back-end development does this, but there is no such thing as "request" in front-end routing.

Front-end routing is to find a component or object whose address matches and render it. There are two ways to change the browser address without sending a request to the server.

One is to add # to the address to deceive the browser. The change of address is due to in-page navigation; the other is to use the HTML5 window. The history function uses the hash of the URL to simulate a complete URL.

vue-router is a set of dedicated routing tool libraries provided by the official, and is a plug-in for vue. We need to introduce it into the vue instance through vue.use() in the global reference,

After using vue-cli to create the project (vue-router confirms y during init initialization)

Let’s first take a look at the structure of the project src and enter the project through cmd In the src directory, execute tree -f > list.txt Generate a structure tree (saved in list.txt):

The structure is as follows:


src
├─assets // 静态资源
│ └─image // 图片
│  
├─components // 组件 
│ └─HelloWorld
│  HelloWorld.vue
│  
└─router // 路由配置
│ └─index.js
│ 
│ App.vue // 默认程序入口
│ main.js
│
Copy after login

1. Open main.js:


import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
 el: '#app',
 router, 
 render: h => h(App) 
})
Copy after login

Line 10 binds the configured route to the vue instance, line 11 Use the render method in the vue instance to draw the vue component (App) to complete the initialization

Render is a new and unique method of vue2. In order to get better running speed, vue2 also uses something similar to react Virtual Dom

2. Then we register several components in components

3. Open router/index.js to configure routing


import Vue from 'vue'
import Router from 'vue-router'
import Singer from '@/components/rank/rank'
Vue.use(Router) // 注册router
export default new Router({
 routes: [
 {
 path: '/',
 name: 'Hello',
 component: MHeader // 路由中指定组件
 },
 {
 path: '/rank',
 name: 'rank',
 component: Rank
 }
 ]
})
Copy after login

Routing mode

Keywords: "mode", "history Mode", "hash mode", "Abstract mode"

We can use the mode in the created Router, such as the parameter mode:history, this value means to use history mode, this mode makes full use of the history.pushState API to complete the URL jump without reloading the page.

If does not use the history mode, when When accessing rank, the route will become:

http://localhost/#rank

and vice versa:

http://localhost/rank

This is the difference between history mode and hash mode. In addition, there is an abstract mode

  • Hash: Use URL hash value as routing,

  • History: Depends on HTML5 History API and server configuration

  • Abstract: Supports all JavaScript running environments, such as node server. If it is found that there is no browser API, the routing will be forced into this mode

Routing and Navigation

Keywords: "router-link", "router-view"

vue-router provides two command tag components to handle this navigation and automatic rendering logic:

  • ——The component view matched by the rendering path,

  • ——Support users to navigate in applications with routing functions

We use two label components to complete a simple page layout:

There is a principle to be clear when using routing That is: Do not directly reference the route definition (that is, do not directly use to='contents/rank/rank' in router-link to direct the route). Once the URL that explicitly references the route definition changes, all All references must be modified.

Refer to the route by name in router-link: pass an object to the to attribute to explicitly declare the name of the route:

Pay attention to the use of v-bind binding (abbreviation:) here, because what needs to be passed to router-link here is an object { name:'rank' } instead of a string

Dynamic routing

Keywords: "Dynamic routing parameters", "params", "$router.params"

vue-router将参数融入到路由的路径定义之内成为路由的一部分,我们称这种参数为"动态路径参数";

使用非常简单,在参数名之前加上":",然后将参数写在路由定义的path内,


 routers:[{
 name:'BookDetails',
 path:'books/:id',
 component:BookDetails 
 }]
Copy after login

1、这样定义之后,vue-router就会自动匹配/books/1、/books/2、...、/books/n 形式的路由模式,因为这样定义的路由的数量是不确定的,所以也称为"动态路由"。

2、在中我们就可以加入一个params的属性来指定具体的参数值:


 <router-link :to="{ name:&#39;BookDetails&#39;,params:{ id:1 } }">
  //...
 </router-link>
Copy after login

3、当我们导航进入图书详情页之后,我们可能需要获取属性指定的参数值(即重新将:id参数读取出来),我们可以通过$router.params来完成:


 export default {
 created () {
  const bookID = this.$router.params.id
 }
 }
Copy after login

嵌套式路由

关键词:"children",

我们利用下面的场景,首页/home/读书详情 页面,读书详情也我们不需要底部的导航区域,但是我们使用之前的路由定义,所有的页面都应该具有想用的底部导航条,按前面的路由结构是不可以导航到图书详情页的,如下:

所以我们就需要另一种定义路由的方式,对前面的路由进行调整,

嵌套式路由又叫做子路由,要将路由显示到子视图中就要相应的子路由与之对应,我们只需要在路由定义中使用children数组属性就可以定义子路由了:


routers:[
 { 
  name:&#39;Main&#39;,
  path:&#39;/&#39;,
  component:Main,
  children:[
  { name:&#39;Home&#39;,path:&#39;home&#39;,component:Home }
  { name:&#39;Me&#39;,path:&#39;me&#39;,component:Me }
  ] 
 },
 { name:&#39;BookDetail&#39;,path:&#39;/books/:id&#39;,component:BookDetail } 
]
Copy after login

需要注意的是以"/"开头的嵌套路径会被当做根路径,所以不要在子路由上加上"/";

重定向路由与别名

关键词:"redirect","alias"

重定向也是通过 routes 配置来完成,下面例子是从 /a 重定向到 /b:


 routes: [
 { path: &#39;/a&#39;, redirect: &#39;/b&#39; }
 ]
// 重定向的目标也可以是一个命名的路由
 routes: [
 { path: &#39;/a&#39;, redirect: { name: &#39;foo&#39; }}
 ]
Copy after login

另外我们需要区别重定向和别名,『重定向』的意思是,当用户访问 /a时,URL 将会被替换成 /b,然后匹配路由为 /b,那么『别名』又是什么呢?

/a 的别名是 /b,意味着,当用户访问 /b 时,URL 会保持为 /b,但是路由匹配则为 /a,就像用户访问 /a 一样:

利用alias给路由设置别名


 routes: [
 { path: &#39;/a&#39;, component: A, alias: &#39;/b&#39; }
 ]
Copy after login

总结

到这里vue路由的基础我们已经总结完毕,我们需要在实战中不断练习,多多的去解决问题,方能更好的使用路由 帮我们完成任务,同时为vue进阶的路由知识打基础。

相关推荐:

vue-router路由参数刷新消失的问题解决方法详解

vue-router路由参数刷新消失改怎么办?

vue-router单页面路由详解

The above is the detailed content of Detailed explanation of vue-router routing and navigation between pages. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to copy a page in Word How to copy a page in Word Feb 20, 2024 am 10:09 AM

Want to copy a page in Microsoft Word and keep the formatting intact? This is a smart idea because duplicating pages in Word can be a useful time-saving technique when you want to create multiple copies of a specific document layout or format. This guide will walk you through the step-by-step process of copying pages in Word, whether you are creating a template or copying a specific page in a document. These simple instructions are designed to help you easily recreate your page without having to start from scratch. Why copy pages in Microsoft Word? There are several reasons why copying pages in Word is very beneficial: When you have a document with a specific layout or format that you want to copy. Unlike recreating the entire page from scratch

I encountered the vue-router error 'NavigationDuplicated: Avoided redundant navigation to current location' in my Vue application - how to solve it? I encountered the vue-router error 'NavigationDuplicated: Avoided redundant navigation to current location' in my Vue application - how to solve it? Jun 24, 2023 pm 02:20 PM

The vue-router error "NavigationDuplicated:Avoidedredundantnavigationtocurrentlocation" encountered in the Vue application – how to solve it? Vue.js is becoming more and more popular in front-end application development as a fast and flexible JavaScript framework. VueRouter is a code library of Vue.js used for routing management. However, sometimes

How to quickly refresh a web page? How to quickly refresh a web page? Feb 18, 2024 pm 01:14 PM

Page refresh is very common in our daily network use. When we visit a web page, we sometimes encounter some problems, such as the web page not loading or displaying abnormally, etc. At this time, we usually choose to refresh the page to solve the problem, so how to refresh the page quickly? Let’s discuss the shortcut keys for page refresh. The page refresh shortcut key is a method to quickly refresh the current web page through keyboard operations. In different operating systems and browsers, the shortcut keys for page refresh may be different. Below we use the common W

How to customize and edit standby mode on iPhone: What's new in iOS 17 How to customize and edit standby mode on iPhone: What's new in iOS 17 Sep 21, 2023 pm 04:01 PM

Standby is a new feature in the iOS 17 update that provides a new and enhanced way to access information when your phone is idle quickly. With StandBy, you can conveniently check the time, view upcoming events, browse your calendar, get weather updates for your location, and more. Once activated, the iPhone will intuitively enter standby mode when set to landscape while charging. This feature is perfect for wireless charging points like your bedside table, or when you're away from your iPhone charging during daily tasks. It allows you to swipe through various widgets displayed in standby to access different sets of information from various applications. However, you may want to modify these widgets or even delete some based on your preferences and the information you need frequently. So let's dive into

What is the horizontal figure 8 on the navigation map? What is the horizontal figure 8 on the navigation map? Jun 27, 2023 am 11:43 AM

The horizontal figure 8 on the navigation map means haze, moderate is a yellow 8 warning signal, and severe is an orange 8 warning signal.

Baidu Maps App latest version 18.8.0 released, introducing traffic light radar function for the first time and adding real-time parking recommendation function Baidu Maps App latest version 18.8.0 released, introducing traffic light radar function for the first time and adding real-time parking recommendation function Aug 06, 2023 pm 06:05 PM

Both Android and iOS versions of Baidu Map App have released version 18.8.0, which introduces the traffic light radar function for the first time, leading the industry. According to the official introduction, after turning on the traffic light radar, it supports automatic detection of traffic lights while driving without having to enter a destination. Beidou High-Precision can position in real time. , 1 million+ traffic lights across the country automatically trigger green wave reminders. In addition, the new function also provides full silent navigation, making the map area more concise, key information clear at a glance, and no voice broadcast, allowing the driver to focus more on driving. Baidu Maps will launch a traffic light countdown function in October 2020, supporting real-time countdown prediction. Judgment, the navigation will automatically display the remaining seconds of the countdown when approaching a traffic light intersection, allowing users to always grasp the road conditions ahead. Traffic light countdown to December 31, 2022

How to Rearrange, Disable, and Delete iPhone Home Screen Pages How to Rearrange, Disable, and Delete iPhone Home Screen Pages Nov 29, 2023 am 08:22 AM

In iOS, Apple allows you to disable individual home screen pages on your iPhone. It's also possible to rearrange the order of home screen pages and delete pages directly instead of just disabling them. Here's how it works. How to Rearrange Home Screen Pages Touch and hold Space on the Home screen to enter jitter mode. Tap the row of dots that represent Home screen pages. In the Home screen grid that appears, touch and drag a page to rearrange it relative to other pages. Others move in response to your dragging. When you're happy with your new arrangement, tap "Done" in the upper right corner of the screen, then tap "Done" again to exit dither mode. How to Disable or Remove Home Screen Pages Touch and hold Space on the Home screen to enter dither mode. Tap to represent home screen

How to implement page jump in 3 seconds: PHP Programming Guide How to implement page jump in 3 seconds: PHP Programming Guide Mar 25, 2024 am 10:42 AM

Title: Implementation method of page jump in 3 seconds: PHP Programming Guide In web development, page jump is a common operation. Generally, we use meta tags in HTML or JavaScript methods to jump to pages. However, in some specific cases, we need to perform page jumps on the server side. This article will introduce how to use PHP programming to implement a function that automatically jumps to a specified page within 3 seconds, and will also give specific code examples. The basic principle of page jump using PHP. PHP is a kind of

See all articles