search
HomeWeb Front-endJS TutorialImplement multiple routing implementations in Vue-Router2.X

Below I will share with you a summary of various routing implementation methods of Vue-Router2.X. It has a good reference value and I hope it will be helpful to everyone.

Note: vue-router 2 is only applicable to Vue2.x version. Below we will talk about how to use vue-router 2 to implement the routing function based on vue2.0.

It is recommended to use npm to install.

npm install vue-router

1. Using routing

In main.js, you need to explicitly install the routing function:

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
Vue.use(VueRouter)

1. Define the component, here we use import from other files

import index from './components/index.vue'
import hello from './components/hello.vue'

2. Define the route

const routes = [
 { path: '/index', component: index },
 { path: '/hello', component: hello },
]

3. Create a router instance, and then Pass routes configuration

const router = new VueRouter({
 routes
})

4. Create and mount the root instance. Inject routes through router configuration parameters, so that the entire application has routing functions

const app = new Vue({
 router,
 render: h => h(App)
}).$mount('#app')

After the above configuration, the components matched by the routes will be rendered to the

Then the App.vue should write like this:

<template>
 <p id="app">
  <router-view></router-view>
 </p>
</template>
index.html里呢要这样写:
<body>
 <p id="app"></p>
</body>

This will render it The page is mounted to the p with the id of app.

2. Redirect redirect

const routes = [
 { path: &#39;/&#39;, redirect: &#39;/index&#39;},  // 这样进/ 就会跳转到/index
 { path: &#39;/index&#39;, component: index }
]

3. Nested routing

const routes = [
 { path: &#39;/index&#39;, component: index,
  children: [
   { path: &#39;info&#39;, component: info}
  ]
  }
]

You can access the info component through /index/info

4. Lazy loading

const routes = [
 { path: &#39;/index&#39;, component: resolve => require([&#39;./index.vue&#39;], resolve) },
 { path: &#39;/hello&#39;, component: resolve => require([&#39;./hello.vue&#39;], resolve) },
]

No need to use lazy loading All components will be loaded at once, and only that component will be loaded when you access that component. For applications with many components, the first loading speed will be improved.

5.

In vue-router 2, router-link>Replace the a tag in version 1

<!-- 字符串 -->
<router-link to="home">Home</router-link>
<!-- 渲染结果 -->
<a href="home" rel="external nofollow" >Home</a>
<!-- 使用 v-bind 的 JS 表达式 -->
<router-link v-bind:to="&#39;home&#39;">Home</router-link>
<!-- 不写 v-bind 也可以,就像绑定别的属性一样 -->
<router-link :to="&#39;home&#39;">Home</router-link>
<!-- 同上 -->
<router-link :to="{ path: &#39;home&#39; }">Home</router-link>
<!-- 命名的路由 -->
<router-link :to="{ name: &#39;user&#39;, params: { userId: 123 }}">User</router-link>
<!-- 带查询参数,下面的结果为 /register?plan=private -->
<router-link :to="{ path: &#39;register&#39;, query: { plan: &#39;private&#39; }}">Register</router-link>

6. Routing information object

1.$route.path

String, corresponding to the path of the current route, is always resolved to an absolute path, such as "/foo/bar".

2.$route.params

A key/value object, including dynamic fragments and full matching fragments. If there are no routing parameters, it is an empty object.

3.$route.query

A key/value object representing URL query parameters. For example, for the path /foo?user=1, $route.query.user == 1, or an empty object if there are no query parameters.

4.$route.hash

The hash value of the current route (without #), if there is no hash value, it is an empty string.

5.$route.fullPath

The URL after completion of parsing, including the full path of query parameters and hash.

6.$route.matched

An array containing the routing records of all nested path fragments of the current route. Route records are copies of objects in the routes configuration array (and in the children array).

Based on the above, a main.js including redirection, nested routing, and lazy loading is as follows:

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App'
Vue.use(VueRouter)
const router = new VueRouter({
 routes:[
 { path: '/', redirect: '/index' },
 { path: '/index', component: resolve => require(['./components/index.vue'], resolve),
  children:[
   { path: 'info', component: resolve => require(['./components/info.vue'], resolve) }
  ]
 },
 { path: '/hello', component: resolve => require(['./components/hello.vue'], resolve) },
 ]
})
const app = new Vue({
 router,
 render: h => h(App)
}).$mount(&#39;#app&#39;)

The above is what I compiled Everyone, I hope it will be helpful to everyone in the future.

Related articles:

How to integrate vue into jquery/bootstrap projects?

Implementing paging in vue.js by clicking the page number to change the page content

How to implement value passing and communication in the vue2.0 component

The above is the detailed content of Implement multiple routing implementations in Vue-Router2.X. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

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 Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment