Use of vue-routing

Posted by xdentan on Sun, 12 May 2019 06:45:01 +0200

Use of Routes

Vue-router is the official routing plug-in for Vue.js. It is deeply integrated with vue.js and is suitable for building single-page applications.The single-page application of Vue is based on Routing and components, which are used to set access paths and map paths and components.Traditional page applications use some hyperlinks to switch and jump pages.In vue-router single-page applications, it is the switch between paths, that is, the switch between components.This article will introduce the features of vue-router in the form of examples. There are six examples, each with a beggar version and the first five with an emperor version.
The beggar version is a HTML page that intermingles all the code, and the emperor version is built on the vue-webpack-simple template.

Named Route

What is Named Routing

1. Official documents: https://router.vuejs.org/zh/guide/essentials/named-routes.html

The advantage of defining a different name for a route when routers configure the route name is that an object can be passed when a route is jumped using the to attribute of router-link to achieve the same effect as router.push:

<router-link :to ="{name:'user',params:{userId:123}}">User</router-link>

Equivalent to

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

Give the route a name so that we can shorten the route when using it

  • Define different names for routes, match by name
  • Define names for different router-view s, and router-link renders the components by name.

Named View

Second, what is a named view?

1. Official documents: https://router.vuejs.org/zh/guide/essentials/named-views.html
Simply put, define different names for different router-view s and render the corresponding components by name

Names are given for views other than the first-level view, which allows you to distinguish between different levels of routing using different levels of view

  • index.js
import Vue from 'vue'
import Router from 'vue-router'
import Goodlists from '@/Goodlists/goods'
import Title from '@/Goodlists/title'
import Img from '@/Goodlists/img'
import Cart from '@/Goodlists/cart'
Vue.use(Router)
export default new Router({
  routes: [
    {
      path: '/goods',
      name: 'Goodlists',
      components:{
        default:Goodlists,
        title:Title,
        image:Img,
      } 
     } 
  ]
})
  • App.vue
<template>
  <div id="app">
    <img src="./assets/logo.png">
    <router-view></router-view>
    <router-view name="title" class="left"></router-view>
    <router-view name="image" class="right"></router-view>
  </div>
</template>

<script>
export default {
  name: 'app'
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
.left,.right{
    float: left;
    width:48%;
    text-align: center;
    border:1px solid red
}
</style>

Dynamic Routing-Routing Parameters-Routing Access

  • vue cli3 configures reverse proxy for 20 minutes
  • Create a new vue.config.js under the root directory
// http-proxy-middleware can be used directly by default in vue.config.js
module.exports = {
devServer: {
proxy: {
'/douban': { // /douban is a tag
target: 'http://api.douban.com', // Target Source
changeOrigin: true, // Modify Source
pathRewrite: {
'^/douban': ''
}
},
'/siku': {
target: 'https://android.secoo.com',
changeOrigin: true,
pathRewrite: {
'^/siku': ''
}
}
}
}
}
  • Routed parameters for 10 minutes
<router-link :to = "{name: 'list',params: {id: xxx}, query: {xxx:xxx}}"></router-link>
  • Routing Access
  • We find that any component that uses routing is collectively referred to as a routing component
  • A $route data is automatically added to the routing component
id: this.$route.params.id
query: this.$route.query.xxx
  • Programmatic navigation for 5 minutes
  • push
  • this.$router.push('/home')
  • this.$router.push({name,params,query})
  • push stores our actions in the browser's history
  • replace
  • this.$router.replace('/home')
  • this.$router.replace({name,params,query})
  • replace did not store our actions in the browser's history and returned a secondary level
  • Business:
  • Button return
  • push
  • replace
  • back
  • go

Routing Advanced Section - Navigation Guard (Routing Guard)

  1. Role: - Similar to [Security]
  • Guard Route
  • enter
  • Example: Bring data in
  • Out
  • Example: Things must be done before they come out
  1. Navigation guards come in three forms
- A: Global Navigation Guard
  1. Global front guard router.beforeEach(fn)
  2. There are three parameters in fn
  3. Global Analysis Guard
  4. At 2.5.0 + you can register a global guard with router.beforeResolve.This is similar to router.beforeEach except that the parse guard is invoked before the navigation is confirmed and after all the guard and asynchronous routing components are resolved.
  5. The resolution of the guard and asynchronous routing components for the entire project must be guaranteed
  6. Global Rear Guard
  • You can do some user-friendly tips
- B: Exclusive Routing Guard
  • Guard hooks written in routing table
  • For routes that are related to the current route, other routes that are not related to it cannot listen for its changes
- C: Component internal guard
  • Pre-guard beforeRouteEnter ((to, from, next) =>{}) within a component
  • Called when navigating into a component
  • This is inaccessible and must be accessed next (vm=>{}) if you want to access this
  • There is no this because the component was not created at this time
  • Case: Data preload (data is obtained before entering a component)
next(vm => { //vm refers to components
const result = JSON.parse(res.data.slice(7,-1)).rp_result.categorys
vm.$set(vm.category,'categorys',result)
})
  • Rear guard within component
  • When ready to leave the component, call
  • this is accessible
  • Update Guard within Component (Routing Passage and Routing Access)
  • Called when the current route changes but the component is multiplexed
  • For example, for a path/foo/:id with dynamic parameters, when jumping between/foo/1 and/foo/2,
  • Because the same Foo components are rendered, the component instances are reused.This hook is called in this case.
  • Can access component instance this
  1. Function: Navigation guard can monitor route changes
  2. noun
  • Front: To enter the current route
  • Post: To leave the current route
  1. About the Use of next
  • next() is equivalent to next (true) to indicate that you can jump from the current route to the target route
  • Next (false) means no pass, meaning no jump from the current route to the destination route
  • next('/login') is equivalent to next({path:'/login'}) jumping the specified route
  • next('/login') is equivalent to next({path:'/login', params,query})
  • Next (fn) data preload
  1. Business: When we get to the first page of a project, but when we don't have a registered account, it actively jumps to the registration/login page
router.beforeEach((to,from,next)=>{
const name = localStorage.getItem('name')
if( name || to.path === '/login' ){
//If there is/ -->/home
next()
}else{
next('/login')
}
})
  1. Route Navigation Guard
    3 Types 7 Routing Listening Hooks
  • Business:
  • Front Guard that monitors route changes across the project globally
  • An exclusive guard of a route that monitors changes in a route
  • Routing changes in the listening routing component Navigation guard within the component

1. Routing

  1. Routing Activation
  • A: Write a class name yourself or use one given by a third party
  • B; Add an active-class attribute to the router-link component
<router-link to = "/home" active-class = "active"/>
  1. Cache for Routes
  • Add a property keep-alive to the router-link component
<router-link to = "/home" keep-alive></router-link>
  1. Routing Animation
  • A: Installing animate.css first allows you to modularize the introduction of yarn add animate.css
  • B: Import'animate.css'in main.js
  • C: Wrap router-view components in transition components
  • D: Add enter-active-class and leave-active-class to the transition component
<transition
enter-active-class="animated slideInLeft"
leave-active-class="animated slideOutLeft"
mode="out-in"
name = "router"
>
<router-view></router-view>
</transition>
  1. Routed data preload (get data before navigation is complete)
  • core
  1. next( vm => { Vue.set(vm.dataAttr,key,value) })
  2. next( vm => { vm.setDate(vm.dataAttr,value )})
  • The difference between the two methods is
  • First method
next(vm => { //vm refers to components
const result = JSON.parse(res.data.slice(7,-1)).rp_result.categorys
vm.$set(vm.category,'categorys',result)
})
//Data in data is defined like this
data () {
return {
data: {
category: null
}
}
}
  • Second method (official website)
next(vm => vm.setData(vm.dataAttr, value))
data () {
return {
category: null
}
}
  1. Lazy Loading of Routes
  2. Concept: means that the corresponding route loads the corresponding routing component - loading the route on demand
  3. Vue Asynchronous Component
  4. Code splitting for webpack
const routerLaayLoad = ( comName ) => {
return () => {
import (/* webpackChunkName: "view-[request]" */ `../components/pages/${view}.vue`)
}
}
const routes = [
{
path: '/',
redirect: '/home'
},
{
path: '/home',
component: () => {
},
children: [
{
path: 'food',
components: {
second: routerLayLoad('home/Food')
},
name: 'food'
}
]
},
{
path: '/category',
component: routerLayLoad('Category'),
/* children: [
{
path: 'list/:id',
component: List,
name: 'list'
}
] */
},
{
path: '/list/:id',
component: routerLayLoad('List'),
name: 'list'
},
{
path: '/login',
component: routerLayLoad('Login')
},
{
path: '/reg',
component: routerLayLoad('Reg')
},
{
path: '/mine',
component: routerLayLoad('Mine')
},
{
path: '/error',
component: routerLayLoad('Error')
},
{
path: '**',
redirect: '/error'
}
]

Topics: Vue Webpack Attribute JSON