Use of Vue basic 5--vue routing

1. Introduction and basic use of Vue routing

1.0 what is routing

Mapping between path and component

1.1 why use routing

Single page application (SPA): all functions are implemented on one html page

Front end routing function: realize business scenario switching

advantage:

  • The overall page is not refreshed, and the user experience is better

  • Easy data transmission and high development efficiency

Disadvantages:

  • High development cost (need to learn expertise)

  • The first load will be slower. Not conducive to seo

1.2 introduction to Vue router

Official website: https://router.vuejs.org/zh/

Vue router module package

It and Vue JS deep integration

You can define - view tables (mapping rules)

Modular

Two built-in global components are provided

Declarative navigation links to automatically activated CSS class es

1.3 Routing - component classification

  • Page component - Page presentation - used with routing
  • Reuse component - display data / commonly used for reuse

1.4 use of Vue router

App.vue - page label and style preparation (copy and continue writing)

<template>
  <div>
    <div class="footer_wrap">
      <a href="#/Find "> find music</a>
      <a href="#/My "> My Music</a>
      <a href="#/Part "> friends</a>
    </div>
    <div class="top">
      
    </div>
  </div>
</template>

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

<style scoped>
.footer_wrap {
  position: fixed;
  left: 0;
  top: 0;
  display: flex;
  width: 100%;
  text-align: center;
  background-color: #333;
  color: #ccc;
}
.footer_wrap a {
  flex: 1;
  text-decoration: none;
  padding: 20px 0;
  line-height: 20px;
  background-color: #333;
  color: #ccc;
  border: 1px solid black;
}
.footer_wrap a:hover {
  background-color: #555;
}
.top {
  padding-top: 62px;
}
</style>

Vue router document

  • install
yarn add vue-router
  • Import route
import VueRouter from 'vue-router'
  • Using routing plug-ins
// In vue, all plug-ins using vue need to call vue use()
Vue.use(VueRouter)
  • Create routing rule array
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
})
  • Replace components with router view
<router-view></router-view>

2. vue Routing - declarative navigation

2.0 sonar navigation - basic use

  1. Vue router provides a global component router link
  2. Router link will eventually render as a link. The to attribute is equivalent to providing the href attribute (to does not need #)
  3. Router link provides the function of declarative navigation and highlighting (with its own class name)
<template>
  <div>
    <div class="footer_wrap">
      <router-link to="/find">Discover music</router-link>
      <router-link to="/my">My music</router-link>
      <router-link to="/part">friend</router-link>
    </div>
    <div class="top">
      <router-view></router-view>
    </div>
  </div>
</template>

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

<style scoped>
/* Other styles are omitted */
.footer_wrap .router-link-active{
  color: white;
  background: black;
}
</style>

2.1 declarative navigation - jump parameters

Pass the value of the to attribute on the router link. The syntax format is as follows

  • /path? Parameter name = value

  • /Path / value - the routing object needs to configure path in advance: "/ path / parameter name"

The corresponding page component receives the passed value

  • $route.query. Parameter name

  • $route.params. Parameter name

  1. Create components / part Vue - prepare to receive parameters and values passed on the route

    <template>
      <div>
          <p>Focus on stars</p>
          <p>Find wonderful</p>
          <p>Find partners</p>
          <p>Join us</p>
          <p>name: {{ $route.query.name }} -- {{ $route.params.username }}</p>
      </div>
    </template>
    
  2. Route definition

    {
        path: "/part",
        component: Part
      },
      {
        path: "/part/:username", // Yes: the path represents the specific value to be received
        component: Part
      },
    
  3. Navigation jump and pass the value to mygoods Vue component

    <router-link to="/part?name=Biography">friend-Biography</router-link>
    <router-link to="/part/Xiao Zhi">friend-Xiao Zhi</router-link>
    

3. vue Routing - redirection and mode

3.0 Routing - redirection

  • The default hash value of web page opening url is / path
  • Redirect is to set which routing path to redirect to

For example, the web page opens by default, matches the route "/", and forcibly switches to "/ find"

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

3.1 Routing - 404 page

Default to a 404 page

Syntax: at the end of the route, the path matches * (any path) – if the previous does not match, the last one will be hit, and the corresponding component page will be displayed

  1. Create NotFound page

    <template>
      <img src="../assets/404.png" alt="">
    </template>
    
    <script>
    export default {
    
    }
    </script>
    
    <style scoped>
        img{
            width: 100%;
        }
    </style>
    
  2. In main JS - modify routing configuration

    import NotFound from '@/views/NotFound'
    
    const routes = [
      // ... Other configurations are omitted
      // 404 at the end (the rule is to compare paths one by one from front to back)
      {
        path: "*",
        component: NotFound
      }
    ]
    

3.2 Routing - mode setting

hash routing, for example: http://localhost:8080/#/home

history routing, for example: http://localhost:8080/home (you need server-side support when you go online in the future, otherwise you will find a folder)

Schema document

router/index.js

const router = new VueRouter({
  routes,
  mode: "history" // Background support is required after packaging and going online. The mode is hash
})

4. vue Routing - programmed navigation

4.0 programming navigation - basic use

Syntax:

this.$router.push({
    path: "Routing path", // Go to router / index JS definition
    name: "Route name"
})
  1. main.js - name the route in the route array
{
    path: "/find",
    name: "Find",
    component: Find
},
{
    path: "/my",
    name: "My",
    component: My
},
{
    path: "/part",
    name: "Part",
    component: Part
},
  1. App.vue - change to span with js programmed navigation jump
<template>
  <div>
    <div class="footer_wrap">
      <span @click="btn('/find', 'Find')">Discover music</span>
      <span @click="btn('/my', 'My')">My music</span>
      <span @click="btn('/part', 'Part')">friend</span>
    </div>
    <div class="top">
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
// Objective: program navigation - js mode jump route
// Syntax:
// this.$router.push({path: "routing path"})
// this.$router.push({name: "route name"})
// be careful:
// Although the name is used to jump, the hash value of the url still switches the path value
// Scenario:
// Easy to modify: name route name (can't be seen on the page, just defined)
// The path can be seen in the hash value of the url (try to conform to the specifications within the group)
export default {
  methods: {
    btn(targetPath, targetName){
      // Method 1: path jump
      this.$router.push({
        // path: targetPath,
        name: targetName
      })
    }
  }
};
</script>

4.1 programmed navigation - jump transfer parameters

Syntax query / params optional

this.$router.push({
    path: "Routing path"
    name: "Route name",
    query: {
    	"Parameter name": value
    }
    params: {
		"Parameter name": value
    }
})

// The corresponding route receives $route params. Parameter name value
// The corresponding route receives $route query. Parameter name value

Special note: using path will automatically ignore params

App.vue

<template>
  <div>
    <div class="footer_wrap">
      <span @click="btn('/find', 'Find')">Discover music</span>
      <span @click="btn('/my', 'My')">My music</span>
      <span @click="oneBtn">friend-Biography</span>
      <span @click="twoBtn">friend-Xiao Zhi</span>
    </div>
    <div class="top">
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
// Objective: to program navigation - jump route parameters
// Mode 1:
// params => $route. params. Parameter name
// Mode 2:
// query => $route. query. Parameter name
// Important: path automatically ignores params
// Recommendation: pass parameters in name+query mode
// Note: if the "hash value and" parameter "on the current url are consistent with the" hash value and "parameter" you want to jump to, the problem of redundant navigation will arise and the route will not be jumped
export default {
  methods: {
    btn(targetPath, targetName){
      // Method 1: path jump
      this.$router.push({
        // path: targetPath,
        name: targetName
      })
    },
    oneBtn(){
      this.$router.push({
        name: 'Part',
        params: {
          username: 'Biography'
        }
      })
    },
    twoBtn(){
      this.$router.push({
        name: 'Part',
        query: {
          name: 'Xiao Zhi'
        }
      })
    }
  }
};
</script>

5. vue Routing - nesting and guarding

5.0 vue route - route nesting

Secondary routing example - Netease cloud music - under discovery music

Router view nested architecture diagram

  1. Create all components needed

    src/views/Find.vue – discover music page

    src/views/My.vue – my music page

    src/views/Second/Recommend.vue – discover music page / recommendation page

    src/views/Second/Ranking.vue – discover music page / leaderboard page

    src/views/Second/SongList.vue – find music page / song list page

  2. main.js - continue configuring Level 2 routing

    The first level routing path is defined from /

    The second level route writes the name directly after the path, and does not need to start with /

    Nested routing writes a routing information object in the children array of the parent route

  3. explain:

    App.vue's router view is responsible for finding music and my music page and switching

    Find.vue's router view is responsible for finding three pages under music and switching

  1. Configure secondary navigation and style (can be copied directly) - in find In Vue
<template>
  <div>
    <!-- <p>recommend</p>
    <p>Ranking List</p>
    <p>song sheet</p> -->
    <div class="nav_main">
      <router-link to="/find/recommend">recommend</router-link>
      <router-link to="/find/ranking">Ranking List</router-link>
      <router-link to="/find/songlist">song sheet</router-link>
    </div>

    <div style="1px solid red;">
      <router-view></router-view>
    </div>
  </div>
</template>

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

<style scoped>
.nav_main {
  background-color: red;
  color: white;
  padding: 10px 0;
}
.nav_main a {
  text-align: center;
  text-decoration: none;
  color: white;
  font-size: 12px;
  margin: 7px 17px 0;
  padding: 0px 15px 2px 15px;
  height: 20px;
  display: inline-block;
  line-height: 20px;
  border-radius: 20px;
}
.nav_main a:hover {
  background-color: brown;
}
.nav_main .router-link-active{
  background-color: brown;
}
</style>
  1. Configure routing rules - Secondary routing display
const routes = [
  // ... Omit others
  {
    path: "/find",
    name: "Find",
    component: Find,
    children: [
      {
        path: "recommend",
        component: Recommend
      },
      {
        path: "ranking",
        component: Ranking
      },
      {
        path: "songlist",
        component: SongList
      }
    ]
  }
  // ... Omit others
]
  1. explain:
  • App.vue, the outer router view is responsible for finding music and switching my music pages

  • Find. The router view in Vue is responsible for finding the component switching corresponding to the sub tab under music

  1. Run - click navigation to see where nested routes are displayed

And the corresponding rules say children

5.1 declaration navigation - class name difference

Observe the style of route nested navigation

  • The hash value path in the router link exact active (exact match) url is exactly the same as the href attribute value. Set this kind of name

  • The hash value in the router link active url contains the path of the href attribute value

5.2 global front guard

Usage example: before jumping the route, judge that the user can go to the < My Music > page only after logging in, and pop up the prompt to return to the find music page if not logging in

  1. Use the fixed method beforeEach on the routing object
// Target: routing guard
// Scenario: when you want to judge the routing permission
// Syntax: router Beforeeach ((to, from, next) = > {/ / execute "before" route jump, and decide whether to jump})
// Parameter 1: route (route object information) target to jump to
// Parameter 2: where to jump route (route object information) source
// Parameter 3: function body - next() will make the route jump and switch normally, next(false) will stay in place, and next ("forced modification to another route path")
// Note: if next is not called, the page remains in place

// Example: judge whether the user logs in and decides to go to "my music" / my
const isLogin = true; // Login status (not logged in)
router.beforeEach((to, from, next) => {
  if (to.path === "/my" && isLogin === false) {
    alert("Please login")
    next(false) // Prevent route jump
  } else {
    next() // Normal release
  }
})

Keywords: Javascript Front-end Vue Vue.js

Added by sloppstack on Sun, 19 Dec 2021 01:08:25 +0200