Use of Routes in vue

Introducing Routing

  • Routing: Is the rule that corresponds to the hash value (# hash) in the browser URL and the display view content
    • Simply put, a route is a set of mapping rules (one-to-one correspondence rules) that are formulated by the developer. -
    • When the hash value (# hash) in the URL changes, the route displays the corresponding view content according to the established rules
  • Why learn routing?
    • In web App s, there is often a single page that shows and manages the functionality of the entire application.
    • SPA is often a complex application. Front-end routing arises to effectively manage all view content.
  • Routing in vue: is the relationship between hash and component, a hash value corresponds to a component

One: Basic use of routing

Preparations (3)

  • Installation: npm i vue-router
  • Introduce:
<script src="./vue.js"></script>
// Note: Introducing routes must follow the introduction of vue, since vue-router works based on Vue
<script src="./node_modules/vue-router/dist/vue-router.js"></script>
  • Instance Routing Object + Mount on vue
    • Instance routing object: const router = new VueRouter()
    • Mount on vue: new Vue (router, data, methods})
    • Verify that the route is mounted successfully depends on opening the page and whether there is one at the end

Specific steps (4)

  • 1. Entrance

  • 2. Routing rules

  • 3. Components

  • 4. Export
# 1. Entry
     //Mode 1: URL address for entry debugging development
     Input url address changes hash value `01-Basic use of routing.html#/one`   
     //Mode 2: Declarative navigation: router-link+to (see below)
# 2. Routing rules
 // path: Routing path
 // component: Routing components to be shown in the future
routes: [
    { path: '/one', component: One }, 
    { path: '/two', component: Two }
]
# 3. Components
 //Use this component name of the return value
const One = Vue.component('one', {
  Template: ` <div>subcomponent one </div> `
})
# 4. Export
 <!--Where to show the export components-->
<router-view></router-view>

#Summary
 Get the entry hash path, find the corresponding component according to the route matching rule, and display it at the corresponding exit location 

2. Cautions for use

  • Entrance
    • The most common entry is declarative navigation router-link
<!-- 
The router-link component is rendered as a tag, and the to attribute is converted to the href attribute of a tag
 The value of the to property, which is essentially a hash value, will participate in routing rules to match components in the future
  -->
<router-link to="/one">Home page</router-link>
  • assembly
const One = {
  template: `<div> Subcomponents one </div> `
}
  • Demo: Multiple components match
<div id="app">
  <!-- 1 Routing Entry: Link Navigation -->
  <router-link to="/one">One</router-link>
  <router-link to="/two">Two</router-link>

  <!-- 4 Routing Exit: Used to display matching routing view content -->
  <router-view></router-view>
</div>

<!--  Import vue.js -->
<script src="./vue.js"></script>
<!--  Import Routing File -->
<script src="./node_modules/vue-router/dist/vue-router.js"></script>
<script>
  // 3 Create two components
  const One ={
    template: '<h1>This is one assembly</h1>'
  }
  const Two =  {
    template: '<h1>This is two assembly</h1>'
  }

  // 0 Create Routing Object
  const router = new VueRouter({
    // 2. Routing rules
    routes: [
      { path: '/one', component: One },
      { path: '/two', component: Two }
    ]
  })

  const vm = new Vue({
    el: '#app',
    //0.Don't forget to associate routes with vue instances!
    router
  })
</script>

3: Entry navigation menu highlighting

  • Two classes have been added to the Click Navigation=>element
<a href="#/one" class="router-link-exact-active router-link-active">One</a>
<a href="#/two" class="">Two</a>
#Another way (meaning only exact matches are allowed)
<router-link to='/' exact></router-link>
  • Modify Mode 1: Modify the style of the class directly
# router-link-exact-active exact match
# router-link-active fuzzy match, when the value of path bungham href on url
.router-link-exact-active,
.router-link-active {
  color: red;
  font-size: 50px;
}
  • Modify Mode 2: Use Existing Class Style=>Modify Default Highlighted Class Name
const router = new VueRouter({
  routes: [],
  // Modify the class name of the default highlighted a label
  // red is already there. Remove the hump behind router and add a class
  linkActiveClass: 'red'
})

IV: Routing Configuration

4.1 Dynamic Routing=>Detail List

Import: List of three mobile phones to click into the details page, just one component to display different data

# Entrance
<router-link to="/detail/1">Mobile 1</router-link>
<router-link to="/detail/2">Mobile 2</router-link>
<router-link to="/detail/3">Mobile 3</router-link>

<router-link to="/detail">Mobile 4</router-link>  How about no parameters????

# Rule (?Indicates transferable but not transferable)
routes: [
  // 2. Routing rules
  { path: '/detail/:id?', component: Detail }
]

# Three ways to get parameters
const Detail =  {
    template: `
        // Mode 1: Direct read in component
        <div> Show details page content....{{ $route.params.id  }} </div>
    `,
    created() {
        // Mode 2: JS direct read
        // Printing will only print once, because the components are multiplexed and the hook function will only execute once each time it comes in
        console.log(this.$route.params.id)
    },
    // Mode 3: Listen for route parameters, why don't you need to listen in depth because a route change corresponds to a new route object (address change)
    watch: {
        $route(to, from) {
            console.log(to.params.id)
        }
    }
}

4.2 Routing Object - $route

  • A route object represents the status information of the currently active route and contains the information parsed from the current URL.

  • A hash value path==>a routing object

  • $route.path

    • Type: string
    • String, which corresponds to the path of the current route, always resolves to an absolute path, such as'/foo/bar'.
    • #Behind? Previous content
  • $route.params

    • Type: Object
    • A key/value object that contains dynamic and fully matched fragments and is empty if there is no routing parameter.
    • A key/value object that contains dynamic and fully matched fragments and is empty if there is no routing parameter.
  • $route.query

    • Type: Object
    • Parameter object
    • A key/value object representing URL query parameters.For example, for path/foo?user=1, $Route.query.user== 1, an empty object if there are no query parameters.
  • $route.hash

    • Type: string

    The hash value of the current route (with #), or an empty string if there is no hash value.

  • $route.fullPath

    • Type: string
    • Full Path
    • The resolved URL contains the query parameters and the full path of the hash.
# Demonstration: 
<router-link to="/detail/4?age=21#one">detail</router-link>
{ path: '/detail/:id?', component: detail } 
//created to print this.$route within a component
> fullPath: "/detail/4?id=001#one"
> hash : "#one"
> params : {id:'4'}
> query : {age : 21}
> path : '/detail/4'

Use wathc to listen on the $route routing object to get information inside

4.3 Nested Routing=> children

Import: url tests parent and child to show child in parent

  • parent's internal additions: < router-view> < /router-view>
  • Add children to the rule
  • The difference between/child and child
    • If it is/child =>then access allows direct access to#/child to access subcomponents
    • If child =>then access should access #/parent/child to access subcomponents
const parent = {
    template: `<p>parent  <router-view> </router-view> </p>`
}
const child = {
    template: `<p>child</p>`
}

const router = new VueRouter({
    routes: [
        {
            path: '/parent',
            component: parent,
            children: [
                #Note the difference between child plus/without plus/here.Add/Use Path Use/Child Not Add/Use/parent/child
                { path: '/child', component: child }
            ]
        }
    ]
})

4.4 Named Routes

  • Sometimes it is easier to identify a route by a name.
  • Especially when linking a route or performing some jumps.===>Scene
  • You can set a name for a route in the routes configuration when you create a Router instance.==>How to name
# name
routes: [
    {
        path: '/parent',
        name: 'parent',
        component: parent
    }
]

# Entry Link + Jump (using path and name conversions)
<!-- Mode 1 : url Manual Writing -->

<!-- Mode 2 : Entry Link Declarative Navigation -->
<router-link to="/parent">click</router-link>
<router-link :to="{ name : 'parent' }">click</router-link>  # Forgot to take: original object type

<!-- Mode 3 : Programmatic Navigation -->
 fn() {
     // this.$router.push('/parent')
     this.$router.push({
         name: 'parent'
     })
 }

4.5 Named View

Import: Sometimes you want to show multiple views at the same time.

Requirements: Access/Root displays three components at the same time

  • Three components
const header = {
    template: `<p>header  </p>`
}
const main = {
    template: `<p>main  </p>`
}
const footer = {
    template: `<p>footer  </p>`
}
  • rule
# Previously, only three header s were displayed
# Effect before presentation 

routes: [
    {
        path: '/',
        components: {
            default: header,
            m: main,
            f: footer
        }
    }
]
  • Exit
<router-view> </router-view>
<router-view name="m"> </router-view>
<router-view name="f"> </router-view>

4.6 Redirection

{path: '/', redirect: '/header'}
{path: '/', redirect: { name: 'header' }}
#Mode three is the function, to is the routing object
redirect: to => {
      // console.log(to)
    return {
        name: 'about'
    }
}

4.7 Component Passwords

  • Get it raw with $route
# Entrance
    <router-link to="/header/3">123</router-link>
# rule
routes: [
    {
        path: '/header/:id',
        component: header,
    }
]
# Get parameters
const header = {
    template: `<p>header  {{ $route.params.id }}  </p>`
}
  • Boolean mode
# Entrance
    <router-link to="/header/3">123</router-link>

# rule
routes: [
    {
        path: '/header/:id',
        component: header,
        // If props is set to true,Route.paramsWill be set as component property
        props: true
    }
]

# Get parameters
const header = {
    // Parameter id as parameter
    props: ['id'],
    template: `<p>header   {{ id }} </p>`
}
  • Object mode
# Entrance
 <router-link to="/header">123</router-link>

# rule
 routes: [
     {
         path: '/header',
         component: header,
         props: { foo: '0000' }
     }
 ]
# assembly
 const header = {
        props: ['foo'],
        template: `<p>header   {{ foo }} </p>`
 }
  • Function mode
# Seat component properties are required just like object mode
# The difference is that props have different values
 props: to => {
     return { foo: '0000' }
 }
 # assembly
 const header = {
        props: ['foo'],
        template: `<p>header   {{ foo }} </p>`
 }
  • Note: Object mode and function mode parameters are in props, so don't pass parameters there for declarative navigation

5: Routing Advancement

5.1 Yuan Information

  • Rule declaration
 routes: [
     {
         path: '/header',
         component: header,
         meta: {
            title: 'XXXX'
         }
     }
 ]
  • Obtain
 created() {
    document.title = this.$route.meta.title
 }
  • Effect:

  • Used as a judgment when navigating a route

5.2 Programmatic Navigation

const one = {
    template: ` 
<div> <button @click="handleClick('back')">Return to the previous page</button>
<button @click="handleClick('push')">Jump two page</button>
<button @click="handleClick('replace')">replace two page</button> 
</div>`,
    methods: {
        handleClick(type) {
            if (type == 'back') {
                // Return
                this.$router.back()
            } else if (type == 'push') {
                // Jump has history
                this.$router.push('/two')
            } else {
                // Replacement has no history
                this.$router.replace('/two')
            }
        }
    }
}
const two = {
    template: `<p>two </p>`
}

5.3 Navigation Guard

router.beforeEach((to, from, next) => {
    // Access login

    if (to.name == 'login') {
        // Next step
        next()
    } else {
        // Stop Jump
        next(false)
        // Jump to the next step
        next({ name: 'login' }) Or use a path  next('/login')
    }
})

Tags: Web Development Vue Mobile Attribute npm

Posted on Sun, 14 Jun 2020 13:24:40 -0400 by DamianTV