Recommended information
Some things in the data are not understood, which can be found in this paper. (No, comment or personal trust)
1. Installation and configuration
Installation:
npm install vue-router -D (-save-dev)
To configure:
For ease of use, a new router.js is created to register and configure VueRouter, such as:
router.js
/**
* Created by yuan on 2/24/2017.
*/
import Vue from "vue";
import VueRouter from "vue-router";
//Global registration
Vue.use(VueRouter);
const router = new VueRouter({
routes:[
]
});
export default router; //Provide interface
Configured in the vue instance: (main.js)
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
new Vue({
el: '#app',
router,//To configure
render: h => h(App)
})
Router configuration
declare type RouteConfig = {
path: string;
component?: Component;
name?: string; // for named routes
components?: { [name: string]: Component }; // for named views (named view component)
redirect?: string | Location | Function;
alias?: string | Array<string>;
children?: Array<RouteConfig>; // for nested routes
beforeEnter?: (to: Route, from: Route, next: Function) => void;
meta?: any;
}
This is excerpted from the document above. The details can be seen in it.
For instance:
const router = new VueRouter({
mode: 'history',
routes: [
//Dynamic path parameters, starting with a colon
{
path: "/user/:id",
component: User,
name: "u",
},
{
path: "/demo",
components: {//Multiple components
demo: Demo,
demo1:Demo1,
}
},
]
});
- mode
Three values: hash | history | abstract- hash: Default value, the address bar will have multiple # numbers: http://localhost:8080/#/
- history: When specified, it's normal. No 65
- abstract: I don't know!!
- routes
Specify addresses and components, etc., after routing matching!
2. Routing Matching
Routing address matching, common types are:
localhost/user/{id}
localhost/user?id=12
(1) Dynamic routing matching
// Dynamic path parameters begin with a colon followed by a component name (a single component)
{ path: '/user/:id', component: User }
When using router-link, you can use router-link directly (with "/" in front of the path to represent the root path):
<router-link to="/user/12">Dynamic matching:/user/12</router-link><br><br>
You can get 12 in the User component through the route object:
<template>
<div>
<h1>User : params </h1>
<h3>{{this.$route.params.id}}</h3>
</div>
</template>
(2) Programmed navigation
Brief introduction: It is to operate through router objects (non-route objects);
For example:
routers an object
{
path: "/user/:id",
component: User,
name: "user", //Named route
}
Programming operation
// Object: path path path under routes under VueRouter
router.push({ path: '/user/12' })
// Named routes: name paths under routes under VueRouter
router.push({ name: 'user', params: { id: 12 }})
// With query parameters, change to / user?id=12
router.push({ path: 'user', query: { id: 12 }})
When used in Component, use this.$router to get the router object and operate on it.
router-link
// router.push(object) This object can be in router-link afferent
<router-link :to="object">
(3) Redirection and aliases
router Object Configuration under VueRouter
Redirect to b
{ path: '/a', redirect: '/b' }
Redirect to a route named foo
{ path: '/a', redirect: { name: 'foo' }}
Redirect the specified function
{ path: '/a', redirect: to => {
// Method Receives Target Routing as a Parameter
// return redirected string path/path object
}
Alias: When accessing b, the address is B and the content is a.
{ path: '/a', component: A, alias: '/b' }
3. Named View
router-view component is a functional component that renders the view component matched by the routing path.
Single component:
{
path: "/home",
component: Home, // Single component
name: "h",
}
Implement under Entry Component: Render Home Component to router-view automatically
// Under App.vue template
<router-view></router-view>
Multi-component: attribute name
{
path: "/demo",
components: { // Multicomponent specifies components to render different router-view s
demo: Demo,
demo1:Demo1,
}
}
Implemented under the entry file: Render different component names to router-view with the same name.
<div >
<router-view name="demo"></router-view>
<router-view name="demo1"></router-view>
</div>
Behavior performance:
Components are rendered into router-view by routing. It is also a component, which can be used in conjunction with transition effect and keep-alive component cache. Keep-alive is guaranteed to be used in the inner layer if used at the same time.
<transition>
<keep-alive>
<router-view></router-view>
</keep-alive>
</transition>
4. Data Loading
(1) vue life cycle
The life cycle of vue corresponds to the life cycle of component, and the hook of life cycle can be used in component to achieve its own purpose.
For example:
Loading data operations can be performed in the create hook (callback)
As shown in the figure above, you can see the hooks of the life cycle (callbacks):
- beforeCreate
- created
- beforeMount
- mounted
- beforeUpdate
- updated
- beforeDestory
Example:
Loading data in mounted
export default {
name: "user",
data(){
return {
post: null,
}
},
mounted(){
let id = this.$route.params.id
this.$http.getUserInfo(id,response(data){
})
}
}
(2) Data acquisition
Routing data acquisition also has hooks (callbacks), two ways:
When I first started looking at it, I was a little confused. Navigation? What the hell? Actually, it's the address bar URL. Let me give you a brief description.
Load the data first, then jump the URL
Before completion, when triggering a route, the data is retrieved in the beforeRouteEnter hook of the route, and the jump is performed after the data acquisition is successful.
For example:
export default {
name: "user",
data(){
return {
post: null,
}
},
watch: {
//Listen for route data changes, route data is read-only!
'$route': 'changData'
},
methods: {
changData: function () {
let id = this.$route.params.id;
console.log("changData : " +id);
this.post = "changData change post !"+id;
},
test: function () {
this.$router.push({path: "/user/188"});
}
},
beforeRouteEnter(to, from, next){
//First complete data loading, then navigation, and then render components
let id = to.params.id;
console.log("beforeRouteEnter : " + id);
//Successful data acquisition
// next(true);
//Failure to retrieve data: intercept no jump
// next(false);
//Assignment of data data data
next(vm => vm.post = ('beforeRouteEnter load'+id));
},
}
beforeRouteEnter hook: The built-in next method performs a jump when next(true), otherwise intercepts the jump
Jump the URL first, then load the data
First complete the jump, and then retrieve the data in the next component lifecycle hook. For example, loading is performed in create and mounted
export default {
name: "user",
data(){
return {
post: null,
}
},
mounted(){
// mounted medium
let id = this.$route.params.id
this.$http.getUserInfo(id,response(data){
})
},
created(){
// created medium
let id = this.$route.params.id
this.$http.getUserInfo(id,response(data){
})
}
(3) Lazy Loading
Routing Lazy Loading (Asynchronous Components)
When packaging applications, js packages become very large, affecting page loading. The components corresponding to different routes are divided into different code blocks. When accessing this route, it is faster to load the corresponding components.
Define asynchronous components: Define existing components as asynchronous components, and then configure routing to achieve lazy loading
Define Foo components as asynchronous components!
const Foo = resolve => {
// require.ensure yes Webpack Special grammar for setting code-split point
require.ensure(['./Foo.vue'], () => {
resolve(require('./Foo.vue'))
})
}
This can also be defined.
const Foo = resolve => require(['./Foo.vue'], resolve)
Using asynchronous components: Using asynchronous components is exactly the same as using components directly
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo
}
]
})
5. advanced
(1) Routing hook (callback)
The data load above has already used the beforeRouteEnter hook data callback;
Routing object hook
- BeforeEvery: Callback hook that executes before routing triggers
Overall situation
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
// to: route routing information object that enters the target
// from: Outgoing route Route Information Object
// next : function , next(true) Execute jumps,next(false) Interception jump
})
local
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
}
}
]
})
- AfterEvery: Hook for post-execution callbacks when routing triggers
// You can also set global and local settings, but notnext Method, only route object
router.afterEach(route => {
// ...
})
Intra-component hooks:
- beforeRouteEnter
- beforeRouteUpdate (2.2 Added)
- beforeRouteLeave
For example:
export default {
name: "user",
data(){
return {
post: null,
}
},
beforeRouteEnter (to, from, next) {
// Called before the corresponding routing of rendering the component is confirm ed
// No Yes! Get component instance `this`
// Because the component instance was not created before the hook was executed
},
beforeRouteUpdate (to, from, next) {
// Called when the current routing changes, but the changed component is reused
// For example, for a path with dynamic parameters, / foo/:id, when jumping between / foo/1 and / foo/2,
// Because the same Foo component is rendered, component instances are reused. This hook is called in this case.
// Accessible component instance `this`
},
beforeRouteLeave (to, from, next) {
// Called when navigation leaves the corresponding routing of the component
// Accessible component instance `this`
}
}
Note that the beforeRouteEnter method can't get a vue instance through this method, because the vue has not been loaded when the method is executed, you can get the vue instance through the next method below.
beforeRouteEnter (to, from, next) {
next(vm => {
// adopt `vm` Access Component Instances
})
}
(2) Transition effect
Because < router-view > is also a component, all transitional effects can be added, such as
<transition>
<router-view></router-view>
</transition>
(3)HTML5 History mode
If it's mixed development, you can use the default hash, when there's a # symbol behind the URL:
http://yoursite.com/index.html/#/home
If a single server runs a SPA application, it can be configured as history, which looks more formal.
http://yoursite.com/user/id
mode attribute
mode Type: string Default value: "hash" (browser environment) | "abstract" (Node.js environment) Optional value:'hash','history','abstract'
6.router and route for Component Injection
router :
Current router instances, commonly used methods:
- router.beforeEach(guard)
- router.afterEach(hook)
- router.push(location)
- router.go(n)
- router.replace(location
- Router. current Route: Get the current route information object
route :
Routing Information Object, Current Routing Status Information, Common Properties
- $route.params
- $route.query
- $route.path
- $route.name
Use within components
- Router objects are used in Component and this.$router call is used.
this.$router.push({path: "/user/188"});
- Get the route information object in Component and call it with this.$route.
this.$route.params.id
Chapter 2: Single Page Applications and Traditional web Applications