1. Basic concepts and principles of routing
1.1 the routing
Routing is a relatively generalized and abstract concept, and the essence of routing is correspondence.
In development, routing is divided into
-
The back-end routing
Concept: Return different content according to different user URL requests
Essence: The mapping between the URL request address and the server
Back-end rendering, which frequently submits forms and causes browser refreshes, has performance issues.
Ajax front-end rendering (solves the submission form browser refresh problem, but does not support browser forward and backward operations)
SPA single page application (the entire site is a single page, content changes through Ajax partial updates, and supports browser address bar forward and back operations)
One of the principles of SPA implementation: URL-address-based hash (changes in the hash result in changes in browser records, but changes in the hash do not trigger new URL requests)
In the process of implementing SPA, the core technology is front-end routing
-
The front-end routing
Concept: Display different page content according to different user events
Essence: Correspondence between user events and event handlers
The front-end route is responsible for the event listening, after triggering the event, through the event function render different content.
-
Realize simple front-end routing
Our requirement is to change the HASH of the URL when clicking on the menu, and control component switching based on the hash change.
Basic Principles:
Combining dynamic components
// Listen for the window's onHashchange event and switch the name of the component to display based on the latest hash value
winow.onhashchange=function(){
// Use location.hash to get the latest hash value
}
Copy the code
1.2 the Vue Router
Vue Router is the official route manager of vue.js. (More in line with the needs of enterprise development)
It is deeply integrated with vue.js core, which can be very convenient for SPA application development
Vue Router provides the following functions:
- HTML5history or Hash mode is supported
- Support nested routines by
- Supported Routing parameters
- Support for programmatic routing
- Support named Routing
Advanced functions of Vue Router
- Navigation guard
- Route lazy loading
2. Basic use of Vue Router
2.1 Basic Procedure
- The installation
- Adding a Routing Link
- Add the route filling bit
- Defining routing Components
- Configure routing rules and create routing instances
- Mount the route to the Vue root instance
1. Install
npm install vue-router
Copy the code
Let’s check to see if the installation is successful in package.json
Because we are using it in a modular project, the routing function must be explicitly installed via vue.use:
import VueRouter from 'vue-router'
Vue.use(VueRouter)
Copy the code
Write it in the entry file main.js
2. Add a route link
// Router-link is a tag provided in vue, which is rendered as a tag by default, and the to attribute is rendered as href by default, The default value of the to attribute will be rendered as a hash address starting with # <router-link to="/user"> here is the user interface </router-link> <router-link To ="/register"> </router-link>Copy the code
3. Add the route filling bit
Also called route placeholders
Components that will be matched by routing rules will be rendered to the router-View location
<router-view></router-view>
Copy the code
4. Define routing components
</div> <script> export default {} </script>Copy the code
</div> </script> export default {} </script>Copy the code
5. Configure routing rules and create routing instances
// Create a route instance object
const router = new VueRouter({
// routes is the routing instance rule
routes: [
// Each routing rule is a configuration object that contains at least two attributes, path and Component
// path indicates the hash address matched by the current routing rule
// component Indicates the component that the current routing rule corresponds to
{path:'/user'.component:User},
{path:'/register'.component:Register},
]
})
Copy the code
6. Mount the route to the Vue root instance
new Vue({
render: (h) = > h(App),
store,
router,
}).$mount("#app")
Copy the code
2.2 Route Redirection
Route redirection means that when A user accesses address A, he or she is forced to redirect to address C to display A specific component page
Using the redirect attribute of the routing rule, you can specify a new route address to conveniently configure route redirection:
const routes = [
// Specify a new routing address using the redirect attribute
{ path: '/'.redirect: '/user' },
{ path: '/user'.component: User },
{ path: '/register'.component: Register }
]
Copy the code
3. Vue Router nesting routine
3.1 Nested routines are determined by usage
1. Nested routines are analyzed by functions
- Click the parent route link to display the template content
- Template content has sub-routing links
- Click the sub-level route link to display the sub-level template content
2. Parent routing component template
- Parent routing link
- Parent component route padding bit
<p>
<router-link to="User">User</router-link>
<router-link to="Register">Register</router-link>
</p>
<div>
<! -- Control component display position -->
<router-view></router-view>
</div>
Copy the code
3. Sublevel route template
- Sub-routing links
- Padding bit of sub-route
const Register={
template:'<div> < H1 >Register component </h1> <hr/> <router-link to="/ Register /tab1"> tab1 </router-link> <router-link to="/register/tab2">Tab2</router-link> <! -- Child route fill position --> <router-view></router-view> </div>
}
Copy the code
4. The nested routine is configured
const routes =[
{path:'/user'.component:User},
{
path:'/register'.component:Register,
children:[
{path:'/register/tab1'.component:Tab1},
{path:'/register/tab2'.component:Tab2}
]
},
]
Copy the code
4. Vue Router matches dynamic routes
4.1 Basic Usage of Dynamic Matching Routes
Application scenario: Routes are matched based on dynamic route parameters
Dynamic path parameter, starting with a colon
const routes = [
{ path: '/user/:id'.component: User },
{ path: '/register'.component: Register }
]
Copy the code
The route component uses $route.params to get route parameters
const User = {
template: {{$route.params.id}} '
}
Copy the code
5. Route components pass parameters
The $route is highly coupled to the corresponding route and is not flexible enough, so you can use Pros to decouple the component from the route
1. The value of props is of the Boolean type
const routes = [
{ path: '/user/:id'.component: User, props: true },
{ path: '/register'.component: Register }
]
Copy the code
const User = {
props: ['id'].template: '
User component -- component id is {{id}}
'
}
Copy the code
2. The value type of props is object type (accept static parameters)
const routes = [
{ path: '/user/:id'.component: User, props: { username: 'orange'.age: 18}}, {path: '/register'.component: Register }
]
Copy the code
const User = {
props: ['username'.'age'].template: '< div > User components -- component id is {{id}} name is: {{username}}, age is {{age}} < / div >'
}
Copy the code
3. The value type of props is function type (accept static and dynamic parameters).
const routes = [
{ path: '/user/:id'.component: User, props: route= > ({ username: 'orange'.age: 18.id: route.params.id }) },
{ path: '/register'.component: Register }
]
Copy the code
const User = {
props: ['username'.'age'.'id'].template: '< div > User components -- component id is {{id}} name is: {{username}}, age is {{age}} < / div >'
}
Copy the code
6. Vue Router Names the route
6.1 Configuration Rules for Named Routes
You can give a routing rule an alias, that is, named Route, to facilitate the path representation.
const routes = [
{
name: 'user'.path: '/user/:id'.component: User,
props: route= > ({ username: 'orange'.age: 18.id: route.params.id })},
{ path: '/register'.component: Register }
]
Copy the code
<router-link to='/user/1'>User1</router-link>
<router-link to='/user/2'>User2</router-link>
<router-link :to='{name:"user",params:{id:3}}'>User3</router-link>
<router-link to='/register'>Register</router-link>
Copy the code
7. Vue Router programmatic navigation
7.1 Two Modes of Page Navigation
Declarative navigation: Navigation by clicking on links is called declarative navigation. For example: <a></a> links in normal pages or <router-link></router-link> in vue
Programmatic navigation: Navigation by calling aN API in the form of JavaScript.
7.2 Basic usage of programmatic navigation
Common programmatic navigation apis are as follows:
- This $router. Push (‘ hash address)
- this.$router.go(n)
const User = {
props: ['username'.'age'.'id'].template: '
User component -- component id is {{id}} name is: {{username}}, age is {{age}} < / h1 > < p > < button @ click = "goRegister" > go to the registration page < / button > < / p > < / div > `
.methods: {
goRegister() {
this.$router.push('/register')}}}Copy the code
The last
If this article helped you, please like it and add it to GitHub blog at github.com/skyblue309. This article summarizes the core knowledge of Vue Router in my opinion. There are also some advanced uses of Vue Router, such as navigation guard, lazy loading of routes, etc. If readers are interested, please refer to the official documentation of Vuex Router.
The official document for Vue Router is router.vuejs.org/zh/