Use of Routing Component 0

I. Overview

Router: Router manages routing;

Routing: Routing is a mapping relationship. A key corresponds to a value, and a key is a path. For background routing,

Value is a callback function for processing requests, and is a component for the front-end routing value.

 

Explain:
1) Officially provided vue plug-ins for SPA (single page)
2) github: https://github.com/vuejs/vue-router
3) Chinese documents: http://router.vuejs.org/zh-cn/
4) Download: NPM install vue-router--save

 

1. Routing usage:

(1) VueRouter(): Builder for creating routers
new VueRouter({// Create Router Instances
// Multiple configuration items (configuration objects)
  })


(2) Routing configuration
  routes: [
{// General Routing
      path: '/about',  
      component: About
    },
{// Automatic Jump Routing
      path: '/',
      redirect: '/about'
    }
  ]


(3) Registered Router
  import router from './router'
  new Vue({
    router
  })


(4) Using routing component labels
Router-link: Used to generate routing links (when clicking on a routing link, you need to display the current routing component on the interface)
   eg: <router-link to="/home">Go to home</router-link>

      <router-link to="/about">Go to about</router-link>


Router-view>: Used to display the current routing component interface
   eg: <div> 

<router-view> </router-view>// indicates that if you click on a routing link (/about), the interface of the routing link is displayed here, that is, in the div.

    </div>

 

2. Caching Routing Component Objects

Normally, when a routing component is switched, the routing component will die, and when switched back, it will be created again.

The caching of routing components is to cache routing components when switching, so that they do not die. Realization:

<keep-alive>
<router-view> </router-view> // cache routing component objects, but usually we will say cache routing component (here to keep About and Home alive)
</keep-alive>

Phenomenon: After inputting ABC into the input box of the About component in the following figure, switch to the Home component, and then cut back to the About component, at which time the input box also shows abc.

 

3. Passing parameters to routing components

Mode 1: Routing Path Carrier Parameters (param/query)

There are two types of parameters here, param parameter and query parameter (the transfer of these two parameters is equivalent). The following example is the transfer of param parameter, if you want to use query parameter type.

Passing parameters, you don't need to write the following: id placeholder, <router-link> routing link, the way the path splicing is the same as before: xxxx?id=1
1) Configuring routing
children: [
  {
Path:'mdetail/: id', //placeholder
    component: MessageDetail
  }
]
2) Routing Path
  <router-link :to="'/home/message/mdetail/'+m.id">{{m.title}}</router-link>
3) Reading Request Parameters in Routing Components
  this.$route.params.id

 

Mode 2: <router-view> Attribute Carries Data

<router-view :msg="msg"></router-view>

In the following example, App.vue passes data to the About component through the msg attribute.

 

4. Programming Routing Navigation

Relevant API
1) this.$router.push(path): equivalent to clicking on a routing link (you can return to the current routing interface)
2) this.$router.replace(path): Replace the current route with a new route (not returning to the current routing interface)
3) this.$router.back(): Request (return) the previous record route
4) this.$router.go(-1): Request (return) the previous record route
5) this.$router.go(1): Request the next record route

 

Use (Basic Routing/Nested Routing)

Download the vue-router package first: NPM install vue-router--save

Non-routing components are generally placed under the components folder, while routing components are generally placed under the views|pages folder.

1. Routing steps:

Step 1: Define routing components

index.html:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <link rel="stylesheet" href="/static/css/bootstrap.css">
  <title>vue_demo</title>

  <style> /*Setting the style when choosing the route,! important means improving the application priority of the specified style rule*/
    .router-link-active {
      color: red !important;
    }
  </style>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>

App.vue:

<template>
  <div>
    <div class="row">
      <div class="col-xs-offset-2 col-xs-8">
        <div class="page-header"><h2>Router Test</h2></div>
      </div>
    </div>

    <div class="row">
      <!--Left side-->
      <div class="col-xs-2 col-xs-offset-2">
        <div class="list-group">
          <!--5.Using routing labels-->
          <!-- Generate routing links -->
          <router-link to="/about" class="list-group-item">About</router-link>
          <router-link to="/home" class="list-group-item">Home</router-link>
        </div>
      </div>

      <!--Right side-->
      <div class="col-xs-6">
        <div class="panel">
          <div class="panel-body">
            <!-- Display the current component -->
            <keep-alive>
              <!--Pass an attribute with a value of abc,If written as:msg="abc", be abc As a variable-->
              <router-view msg="abc"></router-view>
            </keep-alive>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>

<!--Root component-->
<script>
  export default {}
</script>

<style>

</style>

About.vue/Home.vue: User demonstrates basic routing

<template>
  <div>
    <h2>About</h2>
    <p>{{msg}}</p>
    <input type="text">
  </div>
</template>

<!--About assembly-->
<script>
  export default {
    // Receive an attribute that is App Component routing passed over
    props: {
      msg: String
    }
  }
</script>

<style>

</style>
<template>
  <div>
    <h2>Home</h2>
    <div>
      <ul class="nav nav-tabs">
        <!--Using Routing: Routing Links-->
        <li><router-link to="/home/news">News</router-link></li>
        <li><router-link to="/home/message">Message</router-link></li>
      </ul>

      <!--Using Routing: Current Routing-->
      <router-view></router-view>
    </div>
  </div>
</template>

<!--Home assembly-->
<script>
  export default {}
</script>

<style>

</style>

News.vue/Message.vue: Subrouting under Home, user demonstrates nested routing

<template>
  <ul>
    <li v-for="(news, index) in newsArr" :key="index">{{news}}</li>
  </ul>
</template>

<script>
  export default {
    data () {
      return {
        newsArr: ['News001', 'News002', 'News003']
      }
    }
  }
</script>

<style>

</style>
<template>
  <!--Root label div: Only one-->
  <div>
    <ul>
      <!-- :key General Writing index,If there are identity attributes in this object, it's better to write identity attributes.-->
      <li v-for="m in messages" :key="m.id">
        <!--To concatenate strings js Grammar, not grammar html Grammar, so here is:to="" , If used es5 The grammar is :to="''", If used es6 The grammar is:to="``"-->
        <router-link :to="`/home/message/detail/${m.id}`">{{m.title}}</router-link>
        <button @click="pushShow(m.id)">push See</button>
        <button @click="replaceShow(m.id)">replace See</button>
      </li>
    </ul>
    <button @click="$router.back()">Regression</button>
    <hr>
    <router-view></router-view>
  </div>
</template>

<script>
  export default {
    data () {
      return {
        messages: [
          /* {id: 1, title: 'Message001'},
           {id: 3, title: 'Message003'},
           {id: 5, title: 'Message005'}*/
        ]
      }
    },

    mounted () { // Used for asynchronous operation
      // simulation ajax To request data from the background, note that the callback function uses the arrow function
      setTimeout(() => {
        const messages = [
          {id: 1, title: 'Message001'},
          {id: 3, title: 'Message003'},
          {id: 5, title: 'Message005'}
        ]
        this.messages = messages
      }, 1000)
    },

    methods: {
      pushShow (id) {
        this.$router.push(`/home/message/detail/${id}`)
      },

      replaceShow (id) {
        this.$router.replace(`/home/message/detail/${id}`)
      }
    }
  }
</script>

<style>

</style>

MessageDetail.vue: Subrouting under Message

<template>
  <ul>
    <!--$route Represents the current routing-->
    <li>id: {{$route.params.id}}</li>
    <li>title: {{detail.title}}</li>
    <li>content: {{detail.content}}</li>
  </ul>
</template>

<script>
  /*There is no asynchrony, the real situation should be that the details page according to the id passed to the background query.*/
  const messageDetails = [
    {id: 1, title: 'Message001', content: 'message content00111....'},
    {id: 3, title: 'Message003', content: 'message content00222....'},
    {id: 5, title: 'Message005', content: 'message content00333....'}
  ]
  export default {
    data() {
      return {
        detail: {}  // The attributes in it need not be enumerated
      }
    },
    mounted () {// When changing the current routing component parameter data, Component objects will not be recreated, mounted It won't be re-executed, so you need to use it here watch To monitor
      // Simulate asynchronous to background query data
      setTimeout(() => {
        const id = this.$route.params.id // This is passed on. id,It's possible to pass it on and turn it into text, multiply it by one and turn it into a number.
        this.detail = messageDetails.find(detail => detail.id===id*1)
      }, 1000)
    },

    watch: {
      // Method 1
      // $route: function () { // Automatic invocation when changing the current routing component parameter data (component object has the property of $route)
      //   console.log('$route()')
      //   const id = this.$route.params.id
      //   this.detail = messageDetails.find(detail => detail.id===id*1)
      // }
      $route: function (value) { // Mode 2
        console.log(value);
        const id = value.params.id
        console.log(id);
        this.detail = messageDetails.find(detail => detail.id===id*1)
      }
    }
  }
</script>

<style>

</style>

 

Step 2: Register routing components (map routing components to routing)

router/ index.js:

/*
Router Object Module
 */
import Vue from 'vue' //Introduce vue
import VueRouter from 'vue-router' //1. Introduce vue Router component

import About from '../pages/About.vue' //Introducing routing components
import Home from '../pages/Home.vue'
import News from '../pages/News.vue'
import Message from '../pages/Message.vue'
import MessageDetail from '../pages/MessageDetail.vue'

Vue.use(VueRouter) // 2.Declare the use of vue-router Plug-in unit

// 3.Exposing Router Objects(Here is the default exposure, the default exposure, you can use any name when introducing.)
export default new VueRouter({
  routes: [   // All routes in registered applications
    {
      path: '/about',
      component: About
    },
    {
      path: '/home',
      component: Home,
      children: [  // Configuring Subrouting Components
        {
          path: '/home/news', // path Leftmost/Always Represents Root Routing
          component: News
        },
        {
          path: 'message', // This is a simplified way of writing.
          component: Message,
          children: [
            {
              path: 'detail/:id',  // id represents placeholder
              component: MessageDetail
            }
          ]
        },
        {
          path: '', // Set the default display of the subrouting to represent the current, here for/home,Because this is/home Lower self-routing
          redirect: '/home/news'
        }
      ]
    },
    {
      path: '/',  // Setting default requests about,That is, when the root path is requested
      redirect: '/about' // Redirecting Requests/about
    }
  ]
})

main.js: Registered Router

/*
Entry JS
 */
import Vue from 'vue'
import App from './App.vue'
import router from './router' //Introduce routers (because yes) index.js,So it's written directly here../router That's all.


new Vue({//The attribute names of configuration objects are all determined attribute names, which can not be modified arbitrarily.
  el: '#app',
  components: {App}, // Mapping component labels
  template: '<App/>', // Specify the template that needs to be rendered to the page
  router  // 4.Registered routers are equivalent to router: router
})

 

Step 3: Use Routing (Label)

The use of routing mainly uses routing label-routing link <router-link> and current routing <router-view>. App.vue is the main one in the above examples.

News.vue, Messages.

 

Design sketch:

|

Figure 1. Figure 2

Keywords: PHP Vue Attribute github npm

Added by oeb on Sat, 27 Jul 2019 07:44:03 +0300