Routing in vue

Front End Routing: Implementing Business Scene Switching

Because Vue is a single page application (SPA): all functions are implemented on one html page

Advantages of routing:

The user experience is better without refreshing the page as a whole

Easy data transfer and efficient development#Passing in parameters after hash values

Process:

The first load will be slower.

Basic use of vue-router

Official website: Vue Routerhttps://router.vuejs.org/zh/

vue-router module package It is deeply integrated with Vue.js

Installation:

    yarn add vue-router    or    npm  install  vue-router 

main.js entry: needs to be configured under

import VueRouter from 'vue-router'

// In vue, using a plug-in that uses Vue requires calling Vue.use() to use a routing plug-in
Vue.use(VueRouter);


// Create an array of routing rules. and introduce components
const routes = [
  {
    path: "/find",   // 
    component: Find
  },
  {
    path: "/my",
    component: My
  },
  {
    path: "/part",
    component: Part
  }
]
// Create Routing Object-Incoming Rule
const router = new VueRouter({
  routes
})


// Associate to vue instance
new Vue({
  router,
  render: h => h(App),
}).$mount('#app')

Within the component:

<template>
  <div>
    <div class="footer_wrap">
      <a href="#/find ">Discover Music </a>
      <a href="#/my ">my music </a>
      <a href="#/part ">friend</a>
    </div>
    <div class="top">
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
export default {};
</script>

vue-router provides a global component router-link

router-link essentially ends up rendering as a linked to attribute, which is equivalent to providing an href attribute (to does not require a #)

router-link provides declarative navigation highlights (with class names)

Routing parameters:

When jumping a route, you can pass in values to the components corresponding to the route

The to attribute on router-link passes values in the following syntax format:

- /path? Parameter name = value
- /path/: well-defined parameter name - route object is required to configure path in advance: "/path/parameter name"

Step 1: Modify the route

  {
    path: "/my",
    component: Part
  },
  {
    path: "/my/:username", // There are:The path represents the specific value to be received
    component: Part
  },

Step 2: Add parameters to the URL address bar route manually

/my?name=zs

/my/ls

Step 3: Get the data The current component, My Accept the data

/my?name=zs Within the vue component: $route.query.name
/my?age=18 Within the vue component: $route.query.age

 

Within the /my/ls] vue component: $route.params.username

Routing redirection and mode

redirect

const routes = [
  {
    path: "/", // Default hash value path
    redirect: "/find" // Redirect to/find
    // Path after # in browser url changed to / find-rematch array rule
  }
]

Redirect is to set which route to redirect to

After forcing redirection, the rule is matched again in the array

404 Pages

If the route hash value does not match the rules in the array, a 404 page is given by default

Syntax: Route Last, path Match* (Any path) - The previous mismatch hits the last one, displaying the corresponding component page

Create a 404 page in views

<template>
  <img src="../assets/404.png" alt="">
</template>

<script>
export default {

}
</script>

<style scoped>
    img{
        width: 100%;
    }
</style>

Configuration in Routing

//1. Introducing components
import NotFound from '@/views/NotFound'
//2. Configure Routing Rules
const routes = [
  // ...omitted other configurations
  // 404 At the end (the rule is to compare paths one by one from the end)
  {
    path: "*",
    component: NotFound
  }
//If the route does not hit any rules, give an empty 404 page
]

Mode Settings

Two modes: hash mode and history mode

Hisry routing (server-side support is required to go online later, otherwise folders are found)

Configuration

const router = new VueRouter({
  routes,
  mode: "history" // Background support is required when packaging comes online, the pattern is history
})

Programmatic Navigation (Route Jump)

Grammar:

this.$router.push({
    path: "Routing Path", // All go to router/index.js definition
    name: "Route Name"
})

Note: In addition to push, there are also replace and go methods to achieve route jumps

The push method has a history, but replace does not (a simple personal understanding)

See the following picture specifically:

In the routing array, a route can be named by the name property

{
    path: "/find",
    name: "Find",
    component: Find
},
{
    path: "/my",
    name: "My",
    component: My
},
{
    path: "/part",
    name: "Part",
    component: Part
},

Jump Parameters

Syntax: query / params choose one (individual prefers query params)

// Understand the writing:
this.$router.push({
    // path:"/one?id="+id
    path:"/one/"+id
});


//Quey Official:
this.$router.push({
  path: "/one",
  query:{
    // Parameter name: formal parameter
    id:id,
   },
 });


//Official params:
this.$router.push({
  name:"one",
  params:{
     id:id
   }
 });

// Receive $route.params. Parameter name value for corresponding route
// Receive $route.query. Parameter name value for corresponding route

Nesting and guarding of routes

Nested:

1. Configure router-view

2. Configure Routing Rules

const routes = [
  // ...omit the others
  {
    path: "/find",
    name: "Find",
    component: Find,
    children: [
      {
        path: "recommend",
        component: Recommend
      },
      {
        path: "ranking",
        component: Ranking
      },
      {
        path: "songlist",
        component: SongList
      }
    ]
  }
  // ...omit the others
]

Global Front Guard for Routing

Grammar:

Router.beforeEach((to, from, next)=>{//Route jump "before" execute here, decide whether to jump})
Parameter 1: Route (Route Object Information) Target to jump to
Parameter 2: Where to jump the route (Routing Object Information) from
Parameter 3: Function body - next() will allow normal hop switching for routing, next(false) will stay in place, next (forced modification to another routing path)

router.beforeEach((to, from, next) => {
  if (to.path === "/my" && isLogin === false) {
    alert("Please login")
    next(false) // Prevent route jumps
  } else {
    next() // Normal release
  }
})

Summary:

How do I jump between routes? What are the ways

1. <router-link to="Path to jump to page">

2. this.$router.push() jumps to the specified url, adds a record to the history, clicks Back to return to the previous page

3. this.$router.replace() jumps to the specified url, but no records are added to the history. Click Back to the previous page

4. this.$touter.go(n) Jumps forward or backward n pages, either positive or negative

How vue-router configures routing

There are five steps to configure routing in vue:

  1. Introducing vue-router.js

  2. Configure routing path s and components, and generate routing objects

  3. Configure the routing object under the router option in the new Vue

  4. Page hosts routes using <router-view></router-view>

  5. <router-link to="Path to jump"></router-link>Set up route navigation (declarative navigation/programmatic jump)

Routing implementation mode for Vue: hash mode and history mode

Hash mode: in the browser symbol "#", # and # after the character called hash, read with window.location.hash. Features: hash although in the URL, but not included in HTTP requests; used to guide the browser action, is not useful for security on the server side, hash does not reload the page.

Hisry mode: Hisry takes advantage of the new features of HTML5; and provides two new methods: pushState(), replaceState(), which can modify the browser history stack, and monitoring state changes for popState events

Methods used and commonly used in programmatic navigation

Route jump: this.$router.push()

Route replacement: this.$router.replace()

Back: this.$router.back()

Forward: this.$router.forward()

The difference between $route and $route

$route is a routing information object, including routing information parameters such as'path, hash, query, fullPath, matched, name'; $router is a routing instance object, including routing jump methods, instance objects, and so on

Tags: Javascript Front-end Vue.js

Posted on Sun, 12 Sep 2021 17:01:05 -0400 by greyhoundcode