Vue project creation steps and routing router

Time:2020-6-28

1. Create a Vue project step (under Windows Environment). To create a Vue item, check whether the system has the conditions to create the item (whether it has been installed node.js 、webpack、vue-cli)。 CMD opens the terminal.

1.1 if not already installed node.js , install first node.js , after installation, check the node version

node -v

1.2 install Taobao image, and check NPM version after installation: NPM – V

npm install -g cnpm --registry=https://registry.npm.taobao.org

1.3 install webpack

npm install webpack -g

1.4 install Vue global scaffold, vue-cli2. X use NPM install – G Vue cli, vue-cli3. X use NPM install – G @ Vue / cli to install, view Vue version: Vue – V

npm install -g vue-cli

or

npm install -g @vue/cli

1.5 the preparation work is ready, and the formal creation of Vue project is started. There are two ways to create Vue project. My below_ vue_ Pro is the name of Vue project

vue init webpack my_vue_pro

or

vue create my_vue_pro

Vue init is the initialization method of vue-cli2. X. you can use some templates above GitHub to initialize projects. Webpack is the official recommended standard template name. To migrate the vue-cli2. X project to 3. X, you only need to copy the static directory to the public directory. The SRC directory of the old project covers the SRC directory of 3. X. Vue create is the initialization method of vue-cli3. X. at present, the template is fixed, and the template options can be freely configured. The created items are the items of vue-cli3. Different from the structure of vue-cli2, the configuration method is different. Refer to the official documents for specific configuration methods.

If the Vue version is still 2. X, upgrade from vue-cli2. X to the latest version: uninstall first: NPM uninstall – G Vue cli, and then install the latest version of NPM install – G @ Vue / cli

1.6 CD entry project

cd my_vue_pro

1.7 add the required dependent packets, such as Vue route Vue router. You can use NPM install Vue router or Vue add router

npm install vue-router

or

vue add router

1.8 install all dependent packages, NPM install. Uninstall dependency package: NPM uninstall XXX

cnpm install

1.9 running projects, viewing package.json The operation mode in the scripts script in the file, NPM run dev or NPM run serve

npm run serve

2. Vue route

Vue router is Vue.js The official routing manager. It and Vue.js Core deep integration makes it easy to build a single page application. The functions include:

  • Nested route / view tables
  • Modular, component-based routing configuration
  • Routing parameters, queries, wildcards
  • be based on Vue.js View transition effect of transition system
  • Fine grained navigation control
  • Links with automatically activated CSS classes
  • HTML 5 history mode or hash mode, automatically degraded in IE9
  • Custom scroll bar behavior

In order to deepen the understanding of routing, after installing the Vue router package, if the project automatically generates router.js , delete first, let’s write one manually router.js 。 establish router.js After that, add two Vue pages and name Pagea and pageb, as shown in the following figure:

among router.js code

import Vue from 'vue'
import Router from 'vue-router'
//Custom page
import PageA from './views/PageA'
import PageB from './views/PageB'

//Install route to Vue
Vue.use(Router)

const routes = [
 {
  path: '/',
  Redirect: '/ pageb' // redirect. Enter the pageb page by default
 }, {
  //The dynamic path parameter starts with a colon and continues to be appended if there are multiple parameters
  path: '/pageA/:id/:name',
  name: 'pageA',
  component: PageA
 }, {
  path: '/pageB',
  name: 'pageB',
  component: PageB
 }
]

export default new Router({
 //Mode: 'hash', // the default hash mode is "hash". There is also a history mode without "hash"
 routes
})

main.js It is the entry script of Vue project, which is introduced here router.js , incoming routing configuration.

import Vue from 'vue'
import App from './App.vue'
import router from './router.js'

Vue.config.productionTip = false

new Vue({
 Router, // key must be named router
 render: h => h(App)
}).$mount('#app')

2.1 routing view < router View > component and routing navigation < router link > component

On the project launch template page App.vue There is a < router View > routing view component above, which is the same as a placeholder (< slot > slot), and the page replacement caused by the routing change of the page is carried out on the < router View > routing view.

The < router link > is similar to the hyperlink tag < a >. The < router link > has a required attribute to, which is similar to the href attribute of hyperlink < a >. Set the route link to jump.

App.Vue Test code:

<template>
 <div>
 <div>
  < router link to = "/ Pagea / 5188 / Wang Dashi" > Pagea < / router link >|
  <router-link to="/pageB">pageB</router-link>
 </div>
 <router-view/>
 </div>
</template>

2.2 path parameters and query parameters

Path parameters and query parameters are frequently used as a way of data transmission between pages. Path parameter means that as a part of the path, the parameter is configured when configuring the route, and then the parameter must be passed when entering the URL in the browser, otherwise the route page will not be found. For example, the routing configuration of the page a is / page A /: ID /: name, which means that an ID parameter and a name parameter must be passed after the page a, and these two parameters must be passed as part of the path. Then use: this$ route.params To get all the path parameters.

The query parameter is not as strict as the path parameter, which will not be verified by the route. The performance of routing parameters in the URL is to add? Key = value &… After the page link, and then use: this$ route.query To get all query parameters. As shown below:

We print this. $route variable and see the content on the right side of the figure above:

  • this.$ route.name : page name. This name is in router.js The name configured in is also useful. For example, it is used when “named route” is used in < router link >. For example, by setting the name and corresponding parameters in the to attribute of the route link label, the jump effect is the same as setting the route path:
< router link: to = "{Name: 'Pagea', params: {ID: 5188, name: 'Wang Dashi'}" >
  • this.$ route.path : routing path, including path parameters, excluding query parameters
  • this.$ route.fullPath : route full path, including path parameters and query parameters
  • this.$ route.query : path all query parameters
  • this.$ route.params : path all path parameters
  • this.$ route.meta : routing meta information. When configuring routing, you can store some customized data in meta for other purposes
  • this.$ route.matched : it contains some matching information of the route

2.3 route props setting and path parameter acquisition

When setting the page route, if you add a props attribute and set it to true, you can get the parameters directly in the page, and you don’t need to go through this$ route.params To get the parameters. such as router.js Middle part code:

{
  path: '/pageC/:id/:name',
  name: 'pageC',
  Props: true, // if the props property is set to true, the parameters can be directly obtained in the pagec page
  component: PageC
 }

Get the parameter in pagec page:

<template>
 <div>
  <h1>Foshan -- Huang Feihong, from pagec</h1>
  <h3>Why don't you take Wu hook and take 50 states of Guanshan</h3>
  <h3>Path parameter ID:{{ this.id }}, name: {{ this.name }}</h3>
 </div>
</template>

<script>
 export default {
  name: 'pageC',
  Props: ['id ',' name '], // receive path parameters directly
  created(){
   console.log("id: ", this.id, ", name: ", this.name)
  }
 }
</script>

2.4 nested routes.The application interface in real life is usually composed of multiple nested components. Similarly, each dynamic path in the URL corresponds to the nested components in a certain structure. For example, if page pagec is embedded in page B, you need to add a routing view < router View > label in page B as a placeholder for nested page pagec.

Routing part code:

{
  path: '/pageB',
  name: 'pageB',
  component: PageB,
  meta: { isOK: true, type: 9 },
  children: [
   {
    path: 'pageC/:id/:name',
    component: PageC,
    Props: true, // if the props property is set to true, the parameters can be directly obtained in the pagec page
    name: 'subPageC',
    Meta: {requiresauth: true, ID: 51666}, // custom data
   }
  ]
 },

Some codes in pageb page:

<template>
 <div>
  <h1>A cloud -- Luo Xiaohu, from pageb</h1>
  <h3>Thousands of millstones and thousands of blows are still strong. The wind is from southeast to northwest</h3>
  <! -- nested route, nested page placeholder -- >
  <router-view></router-view>
 </div>
</template>

<script>
 export default {
  name: 'pageB',
  created(){
   console.log('...pageB...')
   console.log(this.$route)
  }

 }
</script>

design sketch:

2.5 program navigation.< router link > call clear navigation, there is also a programming navigation, the format is: router.push (location, oncomplete? Onabort?) for example:

//String
router.push('home')

//Object
router.push({ path: 'home' })

//Named route
router.push({ name: 'user', params: { userId: '123' }})

//With query parameter, / register? Plan = private
router.push({ path: 'register', query: { plan: 'private' }})

/*Note: if path is provided, params will be ignored, and query in the above example does not belong to this situation.
Instead, you need to provide the name of the route or the handwritten path with parameters:
*/
const userId = '123'
router.push({ name: 'user', params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
//Params does not work here, that is, if path is provided for programming navigation, the path parameter must be written into path. Query parameters can not be written
router.push({ path: '/user', params: { userId }}) // -> /user

The same programmatic navigation rules apply to the to attribute of the < router link > navigation component

router.replace (location, oncomplete? Onabort?) and router.push (…) the only difference is that it doesn’t add a new record to history, but it’s the same as its method name – replacing the current history record. Declarative navigation replacement usage: < router link: to = “…” replace >, programmatic navigation replacement usage: router.replace (…)

router.go (n) The parameter of this method is an integer, which means how many steps forward or backward in the history record, similar to window.history.go (n)。

//A step forward in browser records is equivalent to history.forward ()
router.go(1)

//One step back recording, equivalent to history.back ()
router.go(-1)

//3 steps forward record
router.go(3)

//If the history record is not enough, it will fail silently
router.go(-100)
router.go(100)

2.6 named views.Sometimes you want to display multiple views at the same time (at the same level), rather than nested display. For example, you can create a layout with two views: sidebar (side navigation) and main (main content). At this time, named views are useful. Instead of having a single exit, you can have multiple views named individually in the interface. If the router view does not have a name set, the default is default.

router.js Middle part code:

{
  path: '/pageD',
  name: 'pageD',
  Components: {// demo named view
   default: PageD,
   tanA: PageA,
   tanB: PageB
  }
 }

App.vue Middle part code:

<router-view/>
 <! -- name the view. If the routing view name matches, the matching page content will be displayed -- >
 <router-view name="tanA"/>
 <router-view name="tanB"/>

2.7 routing mode.The default routing mode is hash mode, that is, the domain name in the address bar is followed by a symbol (this hash is not a hash operation in cryptography). Its characteristics

The hash of the URL is used to simulate a complete URL, so when the URL changes, the page will not reload. However, it doesn’t look very beautiful. In addition, the hash mode route, as a callback address, will cause some trouble when cooperating with some third-party companies. For example, if you want to achieve wechat quick login or obtain wechat user authorization, when wechat user authorization is successful, when you jump back, the code parameter returned by wechat will be inserted in front of the #, so that you can get this C Ode, we need a series of other operations.

There is another mode of routing mode, history mode. This mode is not symbolic, which is in line with our usual usage habits. Make full use of this mode history.pushState API to complete the URL jump without reloading the page.

export default new Router({
 //Mode: 'hash', // the default hash mode is "hash". There is also a history mode without "hash"
 Mode: 'history', // history mode, no symbol
 routes
})

However, to play this mode well, you need background configuration support. Because our application is a single page client application, if there is no correct configuration in the background, when users directly access the browser http://oursite.com/user/id It will return to 404, which is not good.

Therefore, you need to add a candidate resource covering all situations on the server side: if the URL does not match any static resources, the same one should be returned index.html Page, this page is the page that your app depends on.

3. Route navigation guard.

“Navigation” means that the route is changing, and the navigation guard provided by Vue router is mainly used to guard the navigation by jumping or canceling, so as to control the navigation direction. There are many opportunities to be embedded in the route navigation process: global, single route exclusive, or component level.

3.1 global front guard: router.beforeEach

import router from './router.js'

Vue.config.productionTip = false

//Global guard
//Beforeeach, the global guard. When a navigation is triggered, the global guard is called in the order of creation.
router.beforeEach((to, from, next)=>{
 console.log("....beforeEach....")

 //Data verification
 // if (to.fullPath === '/home'){
 // next('/login')
 // }

 if (to.path != '/login'){
 next();
 }
 else {
 setTimeout(()=>{
  next();
 }, 1000)
 }

 console.log(to)
 console.log(from)
 console.log(next);
})

When a navigation is triggered, the global guard is called in the order of creation. Guard is an asynchronous resolution execution. At this time, all guards where the navigation is located are waiting until the resolution is completed.

Each guard method receives three parameters:

  • To: route: the destination routing object to be entered.
  • From: route: the route the current navigation is about to leave
  • Next: function: make sure to call this method to resolve this hook. The execution effect depends on the call parameters of the next method.
    • Next(): the next hook in the pipeline. If all the hooks are executed, the status of the navigation is confirmed.
    • Next (false): interrupts the current navigation. If the URL of the browser changes (maybe the user manually or the browser Back button), the URL address will be reset to the corresponding address of the from route.
    • Next (‘/’) or next ({path: ‘/’}): jump to a different address. The current navigation is interrupted and a new navigation is performed. You can pass any location object to next, and you can set options such as replace: true, name: ‘home’, and any to prop or router.push Options in.
    • Next (error): (2.4.0) + if the parameter passed in next is an error instance, the navigation will be terminated and the error will be passed to router.onError () registered callback.

Make sure to call the next method, otherwise the hook will not be resolved.

3.2 global resolution guard:router.beforeResolve , this and router.beforeEach Similarly, the difference is that before the navigation is confirmed, at the same time, after all components are parsed, the resolution guard is called

3.3 global post hook:router.afterEach However, unlike guards, these hooks do not accept the next function or change the navigation itself:


router.afterEach((to, from)=>{
 console.log("....afterEach....")
 console.log(to)
 console.log(from)
})

3.4 route exclusive guard:Before enter, the parameters are the same as the global guard. The execution order is after the global guard and before the global resolution guard. router.js Part of test code in:

{
  //The dynamic path parameter starts with a colon and continues to be appended if there are multiple parameters
  path: '/pageA/:id/:name',
  name: 'pageA',
  component: PageA,
  //Route exclusive guard
  beforeEnter: (to, from, next) => {
   console.log ("... Exclusive guard of route... Beforeenter...)
   console.log(to)
   console.log(from)
   console.log(next)
   next();
  }
 },

3.5 route guard in the component.When entering a component or when the component path parameter changes, listen separately when leaving the component.

<script>
 export default {
  name: 'pageA',
  //Guard in component
  beforeRouteEnter (to, from, next) {
   // when rendering the corresponding routing of the component is called before confirm.
   //No! Yes! Get component instance ` this`
   //Because before the guard executes, the component instance has not been created
   console.log ('... Guard inside component beforeroute enter...')
   console.log(to)
   console.log(from)
   next();
  },
  beforeRouteUpdate (to, from, next) {
   //Called when the current route changes, but the component is reused
   //For example, for a path with dynamic parameters / foo /: ID, when you jump between / foo / 1 and / foo / 2,
   //Because the same foo component is rendered, the component instance is reused. And the hook will be called in this case.
   //Can access component instance ` this`
   console.log ('... Guard in component beforerouteupdate2222...')
   console.log(to)
   console.log(from)
   next();
  },
  beforeRouteLeave (to, from, next) {
   //Called when the navigation leaves the corresponding route of the component
   //Can access component instance ` this`
   console.log ('... Guard inside component beforeroutleave3333...')
   console.log(to)
   console.log(from)
   next();
  }
 }
</script>

Note: before route enter guard cannot access this, because guard is called before navigation confirmation, so the new component to be launched has not been created. However, you can access the component instance by passing a callback to next. The callback is executed when the navigation is confirmed, and the component instance is used as the parameter of the callback method.

beforeRouteEnter (to, from, next) {
 next(vm => {
 //Access component instance through 'VM'
 })
}

Beforerouteenter is the only guard that supports passing callbacks to next. For beforerouteupdate and beforerouteleave, this is already available, so delivery of callbacks is not supported because it is unnecessary.

Before route leave is usually used to prevent users from leaving before saving changes. This navigation can be cancelled by next (false).


beforeRouteLeave (to, from , next) {
 const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
 if (answer) {
 next()
 } else {
 next(false)
 }
}

Complete navigation resolution process

  • Navigation triggered.
  • Call the exit guard in the deactivated component.
  • Call the global beforeeach guard.
  • Call the beforerouteupdate guard (2.2 +) in the reused component.
  • Call beforeenter in the routing configuration.
  • Resolve asynchronous routing components.
  • Call beforerouteenter in the active component.
  • Call the global beforeresolve guard (2.5 +).
  • Navigation confirmed.
  • Call the global aftereach hook.
  • Trigger DOM update.
  • Call the callback function passed to next in the beforerouteenter guard with the created instance.

———————–Navigation guard call step record—————

1. Beforeeach / / global guard
2. Beforeenter / / route exclusive guard
3. Beforerouteenter / / guard in component
4. Beforeresolve / / global resolution guard
5. Aftereach / / global post hook
6. Beforeroutleave / / called when leaving the page, exclusive in the component (not calling when not leaving the page)

If it is route multiplexing (route remains unchanged and path parameters change), the call steps are as follows:
1. Beforeeach / / global guard
2. Beforerouteupdate / / guard in component
3. Beforeresolve / / global resolution guard
4. Aftereach / / global post hook
5. Beforeroutleave / / called when leaving the page, exclusive in the component (not calling when not leaving the page)

Test Demo: https://github.com/xiaotanit/tan_ Vue

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.