preface
basic instructions for Vue's tools (Vue CLI) and core plug-in (Vue Router).
Vue CLI
Official installation: Portal
First install the scaffold globally.
npm install -g @vue/cli # OR yarn global add @vue/cli
Detect the installed version: vue --version or vue -V
Create a project: Vue create my project or vue ui is created using graphical tools
Content or options are required according to personal configuration.
Final results:
Vue Router
Official installation: Portal
npm installation in existing projects: npm install Vue router
In routing:
- Default address, such as: http://localhost:8080 When / is not written, the default is /, / also represents the root path in the url.
- {path:"/",redirect:"/home"},redirect can redirect the route.
It needs to be at the entrance JS configuration:
import Vue from 'vue' import App from './App.vue' import router from "./routes/router" new Vue({ router, render: h => h(App), }).$mount('#app') // new Vue({ // el:'#app', // router, // })
When you configure the router here, the current component and all future components will have $route $router.
In addition, all components of future generations can use < router View > < router link >
Basic route, dynamic route, nested route
router.js:
// Routing related codes import Vue from "vue" import VueRouter from "vue-router" // Import other components in the project at once import Home from "../components/Home" import About from "../components/About" // VueRouter is a plug-in. To use the plug-in in Vue, you must use Vue use() Vue.use(VueRouter) // Represents a routing rule // Route in vue: a url corresponds to a component const routes = [ {path:"/home",component:Home}, Basic routing {path:"/about/:id",component:About}, Dynamic routing // {path:"/mine/:name/:age/:sex",component:Mine,meta:{address:"bj"}}, { path:"/mine", Nested Route component:Mine, children:[ // { path:"/mine", redirect:"/mine/cart" }, // { path:"/mine/cart", component:Cart }, // { path:"/mine/member", component:Member }, The following is also true OK of { path:"cart", component:Cart },//Comment out { path:"member", component:Member },//Comment out // The following expression is also not OK / indicates the root path // { path:"/cart", component:Cart }, // { path:"/member", component:Member }, Lazy loading of components You can import the following components when using components { path:"cart", component:()=>import("../components/Cart") }, { path:"member", component:()=>import("../components/Member") }, ] }, ] const router = new VueRouter({ // mode:"hash", / / the default hash mode is in the url# mode:"history",//The history pattern does not exist in the url# routes }) export default router;
Router link and router view
In the template:
Router link is a component, which is defined and registered globally. It can be used as a tag.
Router view is a component. It is a built-in component of routing and represents a routing exit.
<template> <div id="app"> <h1>I am App assembly</h1> <hr> <router-link to="/home">home page</router-link> | <router-link to="/about">about</router-link> <!-- Route exit --> <!-- Matching url,The corresponding components need to be put into this outlet (PIT) --> <router-view></router-view> </div> </template>
$route and $router
In the Vue router module, two things are provided:
- $route followed by attribute $route xxx
- $router followed by method $router a()
this.$router.push adds a new record to the history stack.
Route is equivalent to the route object currently being skipped. You can get name,path,params,query, etc. from it.
console.log("$route:",this.$route); console.log("$router:",this.$router); console.log("$route:",this.$route.params.id);//In this way, you can get the id value in the url
route: Front end Routing: vue Routing, one url Corresponding to a component Back end Routing: one url Corresponding to one json
Two modes of routing
the default routing mode used by Vue router is hash mode, which is characterized by a #.
in addition to hash routing, there is also a routing mode called history routing. There is no # number after the url.
difference:
1)history Not behind the route# hash Behind the route#. 2)If you want your url More standardized, recommended history route, history of url More formal. 3)history Routing, many low version browsers do not support well, but hash Routing supports all browsers, history Routing compatibility No, hash Good routing compatibility. 4)If you share third-party information in the project app,yes , we have app Rules, your url Cannot be carried in#At this time, you can only use history routing. 5)history When the route is refreshed or carriage returned, a request may be sent to the back end. If the back end does not process it, a 404 problem may occur, If used in your project history Routing requires back-end cooperation to solve the 404 problem.
Programming navigation
When you click < router link >, this method will be called internally, so click < router link: to = "..." > Equivalent to calling router push(...).
router.push(location, onComplete?, onAbort?)
Calling method: this$ router. push
to navigate to different URLs, use router Push method. This method will add a new record to the history stack, so when the user clicks the browser Back button, it will return to the previous URL.
router.replace(location, onComplete?, onAbort?)
Calling method: this$ router. replace
with router Push is very similar. The only difference is that it does not add a new record to history, but is the same as its method name - replacing the current history record. (therefore, the previous address cannot be returned)
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). (if the number of history records is exceeded, it will fail)
// Take a step forward in the browser record, Equivalent to history.forward() router.go(1) // Step back and record, Equivalent to history.back() router.go(-1)
Write it in the component
<template> <div id="about"> I am About assembly <hr> <button @click="back">return</button> <button @click="goAbout">Go about</button> <button @click="goMine">Fuck me</button> </div> </template> <script> export default{ name:"About", methods:{ back(){ // this.$router.go(-1) this.$router.back(); }, goAbout(){ this.$router.push("/about") }, goMine(){ // this.$router.push("mine") this.$router.replace("mine") } } } </script>
What is the difference between params and query parameters?
params parameter must be name:
The url address bar is different in form:
params parameter transfer: / user /: id = > / user / 123
query pass parameter: / register?plan=private
Navigation guard
official: Portal
Global pre post guard
// As long as the global front guard switches routes, it must be stopped // To where from where from next whether to release router.beforeEach((to, from, next) => { if (to.path !== "/login") { // To go to another route, you must log in before judging whether to log in // If yes, define an islogin on go. Is it true if (window.isLogin) { // Indicates that you are logged in next(); } else { // If you don't log in, return means you're finished and enter the login interface alert("Can't you log in") return next("/login") } } // Release next() }) // Global post guard // The route has entered, is about to leave, is intercepted, cannot be stopped, there is no next, and there is no release problem router.afterEach((to,from)=>{ if(to.path=="/home/mine"){ alert("Are you really leaving me? Woo woo woo~") }else{ console.log("Bye~Inside you!") } })
Guard in assembly
As the name suggests: the guard written in the component.
const Foo = { template: `...`, beforeRouteEnter(to, from, next) { // Before rendering the component, the corresponding route is called before confirm. // no Yes! Get component instance ` this` // Because the component instance has not been created before the guard is executed }, beforeRouteUpdate(to, from, next) { // Called when the current route changes but the component is reused // For example, for a path / foo/:id with dynamic parameters, when jumping between / foo/1 and / foo/2, // Since the same Foo component will be rendered, component instances will be reused. The hook will be called in this case. // Can access component instance ` this` }, beforeRouteLeave(to, from, next) { // Called when the navigation leaves the corresponding route of the component // Can access component instance ` this` } }
This exit guard is usually used to prevent users from leaving suddenly before saving their changes. The navigation can be cancelled by next(false).
beforeRouteLeave (to, from, next) { const answer = window.confirm('Are you really leaving? You haven't saved it yet!') if (answer) { next() } else { next(false) } }
Route exclusive guard
You can directly define the beforeEnter guard on the routing configuration:
const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, beforeEnter: (to, from, next) => { // ... } } ] })