[Vue]: Routing

What is routing

  1. For the average website, all hyperlinks are URL addresses, URL addresses corresponding to all of the resources corresponding to the server;
  2. For single-page applications, mainly realized by switching between different pages in the URL hash (# number), while, a hash features: HTTP request does not contain relevant content hash; therefore, a single page of the application the main page jump implemented hash;
  3. In the single-page applications in this manner to switch the page by changing the hash, called the front end of the route (route different from the rear end);

Use vue-router in the vue

The basic use of the route includes the following steps:

  • Introduction vue-router.js, you can also npminstalled later reintroduced
  • Create a template object
  • Creating a route object, when introduced vue-routerafter a packet, the windowglobal object, there is a route constructor called VueRouter, at newthe time of route object, the constructor may pass a configuration object. Configuration object routesrepresents the routing matching rules , each routing rule, is an object, the object of this rule who, with two required attributes:
    • pathIt represents listens for routing link address;
    • componentHe said that if the route is matched to the front path, then display componentthe corresponding component properties, note: componentthe property value must be a component of template objects, can not be a reference to the name of the component.
  • router: routerObjThe routing rule object, registered vm instance, used to monitor changes in the URL, and then display the corresponding components
  • router-viewIs vue-routerprovided element, specifically used as a placeholder, the display component to match in the future to match the component routing rules, it will show this to router-viewgo
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="./lib/vue-2.4.0.js"></script>
  <script src="./lib/vue-router-3.0.1.js"></script>
</head>

<body>
  <div id="app">
    <a href="#/login">登录</a>
    <a href="#/register">注册</a>
    <router-view></router-view>
  </div>

  <script>
    var login = {
      template: '<h3>登录组件</h3>'
    }

    var register = {
      template: '<h3>注册组件</h3>'
    }

    var routerObj = new VueRouter({
      routes: [
        { path: '/login', component: login },
        { path: '/register', component: register }
      ]
    })
    var vm = new Vue({
      el: '#app',
      router: routerObj
    })
  </script>
</body>

</html>

The official recommended router-linkinstead of <a>doing Components Navigation

<router-link to="/login">登录</router-link>
<router-link to="/register">注册</router-link>

router-linkThe default rendering into a alabel, you can tagattribute specifies the elements to be rendered

<router-link to="/login" tag="span">登录</router-link>

You can be /mapped to log the specified component

{ path: '/', component: login }

Recommended redirectredirection

{ path: '/', redirect: '/login' }

The default route is activated, the application of router-link-activestyle, the style change can be defined to highlight

.router-link-active {
    color: red;
    text-decoration: underline;
}

To modify the default style, a constructor may be rerouted by the attribute linkActiveClassto specify a custom style to be applied

var routerObj = new VueRouter({
    routes: [
        { path: '/', redirect: '/login' },
        { path: '/login', component: login },
        { path: '/register', component: register }
    ],
    linkActiveClass: 'myactive'
})

Animation route switching is provided: the use of transitionlabels wrapped router-view, and define v-enter, v-leave-to, v-enter-active, v-leave-activethe style, by modeproperty switching mode animating

<transition mode="out-in">
    <router-view></router-view>
</transition>

Passing parameters in the routing rule

  • 1.1 using a query string parameter passed to the routing, the need to modify routing rules pathproperties
<router-link to="/login?id=10&name=zs">登录</router-link>
  • 1.2 subassembly by this.$route.query.属性名acquisition parameters
var login = {
    template: '<h1>登录 --- {{ $route.query.id }} --- {{ $route.query.name }}</h1>'
}
  • 2.1 :placeholder to pass parameters into routing rules need to transform
{ path: '/login/:id/:name', component: login }
  • 2.2 transmission parameters can be written as
<router-link to="/login/12/zs">登录</router-link>
  • 2.3 subassembly by this.$route.params.属性名acquisition parameters
var login = {
    template: '<h1>登录 --- {{ $route.params.id }} --- {{ $route.params.name }}</h1>'
}

Use childrenproperty nested implement routing

  • The use of childrenproperty, to achieve sub-routing, while the sub route pathin front, do not take /, otherwise it will start to root request.
<div id="app">
  <router-link to="/account">Account</router-link>
  <router-view></router-view>
</div>

<template id='tmpl'>
  <div>
    <h3>Account组件</h3>
    <router-link to="/account/login">登录</router-link>
    <router-link to="/account/register">注册</router-link>
    <router-view></router-view>
  </div>
</template>
<script>
  var account = {
    template: '#tmpl'
  }

  var login = {
    template: '<h4>登录组件</h4>'
  }

  var register = {
    template: '<h4>注册组件</h4>'
  }

  var router = new VueRouter({
    routes: [
      {
        path: '/account',
        component: account,
        children: [
          { path: 'login', component: login },
          { path: 'register', component: register }
        ]
      }
    ]
  })

  var vm = new Vue({
    el: '#app',
    router
  })
</script>

Named achieve classic layout view

  • Route learned earlier matching rules { path: '/', component: header }, represented showing the component, and routing and assembly when mated to a one-route.
  • By componentsyou can specify many relationship routing and assembly, note that componentsinstead component.
    By router-viewtag nameattributes, represent the future to the router-viewassembly show. If there is no nameattribute, show componentsthe defaultproperties of the corresponding component.
  1. html code structure:
<div id="app">
  <router-view></router-view>
  <div class="container">
    <router-view name="left"></router-view>
    <router-view name="main"></router-view>
  </div>
</div>
  1. JS code:
<script>
  var header = {
    template: '<h1 class="header">Header头部区域</h1>'
  }

  var leftBox = {
    template: '<h1 class="left">Left侧边栏区域</h1>'
  }

  var mainBox = {
    template: '<h1 class="main">mainBox主体区域</h1>'
  }

  var router = new VueRouter({
    routes: [
      {
        path: '/', components: {
          'default': header,
          'left': leftBox,
          'main': mainBox
        }
      }
    ]
  })

  var vm = new Vue({
    el: '#app',
    router
  })
</script>
  1. CSS style:
<style>
  html,
  body {
    margin: 0;
    padding: 0;
  }

  .header {
    background-color: orange;
    height: 80px;
  }

  h1 {
    margin: 0;
    padding: 0;
    font-size: 16px;
  }

  .container {
    display: flex;
    height: 600px;
  }

  .left {
    background-color: lightgreen;
    flex: 2;
  }

  .main {
    background-color: lightpink;
    flex: 8;
  }
</style>

watchUse of property

watchThings datachange in the specified data

The first text box to enter firstname, the second text box to enter lastname, the third output text box fullname, html following structure

<div id="app">
  <input type="text" v-model="firstname"> + 
  <input type="text" v-model="lastname"> = 
  <input type="text" v-model="fullname">
</div>

Use watchproperty can monitor datathe specified changes in the data, and then trigger the watchcorresponding functionhandler.

var vm = new Vue({
  el: '#app',
  data: {
    firstname: '',
    lastname: '',
    fullname: ''
  },
  watch: {
    'firstname': function () {
      this.fullname = this.firstname + '-' + this.lastname
    }
  }
})

Note that watchthe property is free if -possible without single quotation marks, if the content -to be single quotes, the function may be abbreviated as follows:

firstname() {
  this.fullname = this.firstname + '-' + this.lastname
}

In addition, the monitoring function can accept two parameters (newValue, oldValue), the value after the change, and the value before the change, respectively, and therefore this.firstnamecan be newValuereplaced, if not used oldValue, can not write parameteroldValue

firstname(newValue, oldValue) {
  this.fullname = newValue + '-' + this.lastname
}

Change monitor route object

Monitoring the route change, in fact, it is to monitor this.$route.pathchanges in properties

'$route.path': function(newValue, oldValue) {
  if (newValue == '/login') {
    console.log('欢迎进入登录页面')
  } else {
    console.log('欢迎进入注册页面')
  }
}

computedUsing the calculated property

  • In computedcan be defined in a number of properties, which is called the calculated property , the nature of the property is a calculation method, but when we use these calculations attributes, their names are to be used directly as a property; does not put computing property, as a way to call; therefore, although datanot included in fullnameproperty, but htmlcan still use the label v-modelbinding computedcalculation attribute propertiesfullname
  • When referring to calculate property, must not add ()to call directly to the property to use it like a normal enough
  • As long as computed attribute this functionto any interior, the use of datathe data has changed, it will recalculate the calculated value of the property immediately.
  • Evaluates the attribute calculation are cached, directly next time; attribute calculation method if any data references are not changed over, it is not re-calculated property evaluation;
var vm = new Vue({
  el: '#app',
  data: {
    firstname: '',
    lastname: ''
  },
  computed: {
    'fullname': function(){
      return this.firstname + '-' + this.lastname
    }
  }
})
  • It has the definition getterand settercalculation of properties:
<div id="app">
    <input type="text" v-model="firstName">
    <input type="text" v-model="lastName">
    <!-- 点击按钮重新为 计算属性 fullName 赋值 -->
    <input type="button" value="修改fullName" @click="changeName">

    <span>{{fullName}}</span>
</div>

<script>
    // 创建 Vue 实例,得到 ViewModel
    var vm = new Vue({
        el: '#app',
        data: {
            firstName: 'jack',
            lastName: 'chen'
        },
        methods: {
            changeName() {
                this.fullName = 'TOM - chen2';
            }
        },
        computed: {
            fullName: {
                get: function () {
                    return this.firstName + ' - ' + this.lastName;
                },
                set: function (newVal) {
                    var parts = newVal.split(' - ');
                    this.firstName = parts[0];
                    this.lastName = parts[1];
                }
            }
        }
    });
</script>

watch, computedAnd the methodscontrast between

  1. computedThe results are cached attributes, the attribute change responsive unless dependent recalculated only. The main property to use as;
  2. methodsThe method represents a particular operation, main writing business logic;
  3. watchAn object key is an expression of the need to observe the value corresponding callback function. Is mainly used to monitor specific changes in the data, thereby performing certain business logic operation; it can be considered computedand methodsa combination thereof;

Guess you like

Origin www.cnblogs.com/moon1992/p/11075020.html