- This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.
Basic use of router
main.js
- Mount the routing
import Vue from 'vue'
import App from './App'
// Imports the contents of the router folder by default
import router from './router'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,// Mount the route and inject the route as a Vue object for easy use
render: h= > h(App)
})
Copy the code
App.vue
- There are two ways to route hops
Router-link Other attributes:
- To: Indicates the jump path
- Tag: What HTML element can a router-link tag be rendered to
- Replace (no return record): Specify router-link in history mode to use replaceState instead of a pushState()
- Active-class: if the route is successfully matched, an active-class attribute class name is set for the currently selected element
<template>
<div id="app">
<! -- Router-view is used to display the router rendering component, and the mounted component is switched. Other contents are not changed.
<router-view></router-view>
<! -- Router-link is rendered as a tag by default -->
<! -- to click on the path to render,tag and HTML tag to render replace cannot return to the previous page -->
<! When a route is active, vue automatically adds a class to the route. You can also use active-class to change the class name.
<! -- <router-link to="/home" tag="button" replace active-class="active" > </router-link> <router-link to="/about" Replace > About </router-link> -->
<button @click="homeClick">Home page</button>
<button @click="aboutClick">about</button>
</div>
</template>
<script>
export default {
name: "App".methods: {
homeClick() {
// The path can also be modified with code
// Vue defines a router attribute for each element
// Push = pushState After clicking, you can return to the previous step
// this.$router.push('/home')
this.$router.replace("/home");
},
aboutClick() {
this.$router.replace("/about"); ,}}};</script>
Copy the code
Index. js in router folder (remove router)
Routing mode:
Hash: Historical mode that does not generate page refresheshistory: No history, no page refreshCopy the code
Note: Repeated routing clicks will result in an error, demoting the router plugin to version 3.5 or below
You can configure the class name of the active route. If multiple router-links require class names, you can configure the class name in the route
// Reference file
import Vue from 'vue'
import Router from 'vue-router'
import Home from '.. /components/Home'
import About from '.. /components/About'
Use Vue. Use (plug-in) to install the plug-in
Vue.use(Router)
// export default (export) passes the Router object to the vue instance
export default new Router({
2. Create a Router object
// Configure the mapping between routes and components
// routes is a fixed form
routes: [{path:' './ / redirection
redirect:'/home'
},
{
// Define the path
path: '/home'.name: 'HelloWorld'./ / display component
component: Home
},
{
path:'/about'.component:About / / component name},].mode:'history'.// Globally configure the class name of the active route. This class name is used for active (dynamic) routes
linkActiveClass:'active'
})
Copy the code
Dynamic parameter transfer + programmatic navigation
You can add /: ID to a route path to change it into a dynamic route
App.vue
<template>
<div id="app">
<! </router-link> </router-link to="/user"> </router-link> -->
<! -- Added two navigation to user, using different to -->
<! -- <router-link to="/user/1" tag="button">1</router-link> <router-link to="/user/2" tag="button">2</router-link> -->
<! -- Dynamic routing -->
<! -- <router-link :to="'/user/'+user1" tag="button">1</router-link> <router-link :to="'/user/'+user2" tag="button">2</router-link> -->
<! Programmatic navigation, click trigger event function -->
<button @click="toHome">Home page</button>
<button @click="toUser">The user</button>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App'.data() {
return {
user1:'δΈ'.user2:'δΊ'}},components: {},methods: {
toHome(){
/ / to the home page
// In the function, get the route object through $router under the component instance object and push it to the route to jump to
// this.$router. Push ('/home')// this
// this.$router.push({path:'/home'})// Jump as an object
this.$router.replace('/home')//replace has no history
},
toUser(){
/ / to the user
this.$router.push('/user/'+this.user2)
}
},
}
</script>
Copy the code
User. Vue components
<template>
<div id="user">
<h2>User component</h2>
<h3>welcome<span>{{uname}}</span>Go to the user page</h3>// Output one or two toggles<! $router = $route; $router = $route;
<h4>{{$route.params.id}}</h4>
</div>
</template>
<script>
export default {
computed: {uname(){
// this is to see what methods the current component has
// console.log(this);
// Print the name
return this.$route.params.id
}
}
}
</script>
Copy the code
Embedded routines by
Use this.$route to fetch active components;
This.$router: Gets the entire router route
// Configure routing information
import Vue from 'vue'
import Router from 'vue-router'
Use vue.use to install the plug-in
Vue.use(Router);
// Reference the component
import Home from '.. /components/Home.vue'
import User from '.. /components/User.vue'
import News from '.. /components/News.vue'
import Msg from '.. /components/Msg.vue'
// Configure the reference relationship between the route and the component
const routes =[
{
path:'/'.// Redirect
redirect:'/home'
},
{
path:'/home'.component:Home ,
// Use nested routines with the children attribute
children:[
{
path:'/home'.redirect:'/home/news'
},
{// Child paths with slashes are treated as root paths
path:'news'.component:News
},
{
path:'msg'.component:Msg
},
]
},
{
path:'/user/:id'.component:User
},
]
// Create vue-router
const router = new Router({
routes,
/ / not history
mode:'history'.linkActiveClass:'active'
})
// 3. Export router to vue instance
export default router
// $route: points to active components
$router: indicates the entire router route
Copy the code
Route parameter transmission and lazy loading
The index of the router. Js
/ Configure route informationimport Vue from 'vue'
import Router from 'vue-router'
Use vue.use to install the plug-in
Vue.use(Router);
/ / lazy loading
const User = () = > import('.. /views/User.vue')
const Info = () = > import('.. /views/info.vue')
const routes =[
/ / {
// path:'/home',
// name:'Home',// Name the route
// component:Home
// },
{
// Configure dynamic routing
path:'/user/:id'.name:'User'./ / lazy loading
component:User
},
{
path:'/info'.name:'Info'.component:Info
},
]
const router = new Router({
routes,
/ / not history
mode:'history'.// linkActiveClass:'active'
})
// 3. Export router to vue instance
export default router
Copy the code
The Info components
<template>
<div id="info">
<h2>This is the information component</h2>//$route receives parameters<h3>Name: {{$route. The query. The name}}</h3>
<h3>Age: {{$route. Query. Age}}</h3>
</div>
</template>
Copy the code
The User component
<template>
<div id="user">
<h2>The user information</h2>
<! $route ->// There are two params. ids in the page, click on which id is displayed<h3>User id {{$route.params.id}}</h3>
</div>
</template>
Copy the code
App.vue
<template>
<div id="app">
<router-link to="/user/2021">user</router-link>|
<router-link to="/info">info</router-link>
<! Programmatic navigation -->
<button @click="toUser">user</button>
<hr />
<! - use the path -- -- >
<! -- <router-link :to="{path:'/user/'+userId}">user--path</router-link><br> -->
<! -- name,params -->
<router-link :to="{name:'User',params:{id:userId}}">user--name</router-link>
<div>
<! -- Pass the parameter via query, /info? Name = 22 & sex rh&age = = male - >
<router-link :to="{path: '/ info, the query: {name:' rh, age: 22, sex: 'male'}}">info-path</router-link>
<! Programmatic navigation, /info? Name = intent &age=22 -->
<button @click="toInfo">info</button>
</div>
<hr>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: "App".data() {
return {
userId: '20211'}; },methods: {
// Route parameters:
// Query and path work together
// Params works with name
// name: indicates the named route
toUser() {
/ / params refs
this.$router.push({ name: "User".params: { id: "567"}}); },toInfo(){
// No historical record
/ / $router to participate
this.$router.replace({name:'Info'.query: {name:'ζζ'.age:22,}})}},};</script>
Copy the code
Guard hook (global + exclusive + guard within component)
The login page
<template>
<div id="login">
<h3>The login</h3>Account:<input type="text" name="" id="" v-model="userName" />Password:<input
type="text"
v-model="userPass"
/>
<button @click="login">The login</button>
</div>
</template>
<script>
export default {
data() {
return {
userName: "".userPass: ""}; },methods: {
login() {
// Assign uname and upass to the window object;
var name = window.uname = "admin";
var pass = window.upass = "123";
if (this.userName == name && this.userPass == pass) {
alert("Login successful");
// Go to the home page
this.$router.replace("/");
}else{
alert('Wrong account number')}},},};</script>
Copy the code
routing
// Configure routing information
import Vue from 'vue'
import Router from 'vue-router'
Use vue.use to install the plug-in
Vue.use(Router);
/ / lazy loading
const User = () = > import('.. /views/User.vue')
const Info = () = > import('.. /views/info.vue')
const Login = () = > import('.. /views/Login.vue')
const routes =[
{
// Configure dynamic routing
path:'/user/:id'.name:'User'./ / lazy loading
component: User,// Exclusive route guard
beforeEnter(to, from, next){
next()
}
},
{
path:'/info'.name:'Info'.component:Info
},
{
path:'/Login'.name:'Login'.component:Login
},
]
const router = new Router({
routes,
/ / not history
mode:'history'.// linkActiveClass:'active'
})
// Global front hook: beforeEach
// Do something before entering
// to: route to go
// from: route to
// next: release, default is false
// You can also access the account password in window
router.beforeEach((to,from,next) = >{
if(to.name ! = ='Login') {// Verify login
if(window.uname && window.upass){
next();
}else{
alert('Please log in first')
next('/Login')
}
}
next();
})
// global postfix
// to: route to jump to
// from: route to
router.afterEach((to,from) = >{
console.log('welcome'+window.uname);
})
export default router
Copy the code
About.vue
<template>
<div class="about">
<h1>about</h1>
<button @click="toA">A</button>
<button @click="toB">B</button>
<div style="border:2px red solid">
<router-view></router-view>
</div>
</div>
</template>
<script>
export default {
name: "About".data() {
return {
msg: "This is the routing guard for the component."}; },methods: {
toA(){
this.$router.push('/about/a')},toB(){
this.$router.push('/about/b')}},// The route guard within the component
// beforeRouteEnter corresponds to the beforeCreate for the life cycle
beforeRouteEnter(to, from, next) {
// Cannot get the component instance
// When the guard executes, the component instance has not been created
next();
},
beforeRouteLeave(to, from, next) {
// The route is called when navigating away from the component
// Component instances can be accessed
// console.log(this.msg);
next();
},
beforeRouteUpdate(to, from, next) {
// The current route changes, but only when the component is reused
// This is triggered only when a child route jumps between a and Bnext(); }};</script>
Copy the code
Supplement:
To resolve the error of clicking route repeatedly:
1. Add the following code to the routing page:
//Router Specifies the route name
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location){
return originalPush.call(this,location).catch(err= >err);
}
Copy the code
2. Alternatively, directly reduce the router version to earlier than 3.5.
Router:
- Router is an instance of VueRouter. If you want to navigate to different urls, you use router as instance VueRouter. If you want to navigate to different urls, you use router.push
- $route indicates the current router jump object, which can obtain name, path, query, and params
The last
If it is helpful to you, I hope I can give π comment collection three even!
Bloggers are honest and answer questions for free β€