Vue-Router (super detail)

本章要给大家带来的内容是相关Vue中的组件以及一系列常用属性。
本章合适人群囊括了除已有开发经验人员以外的小白新手,
从how、why、what三个    角度来让大家理解并使用该技术

table of Contents

Routing principles

  • After the traditional development mode change url immediately initiate a request, response of the entire page, rendering the entire page
  • SPA anchor will not initiate a request to change the value, ajax request initiated locally change the page data
    • Page does not jump better user experience

SPA

  • single page application (single-page application)
  • Front-end routing
    • Anchor value monitoring
    • ajax obtain dynamic data
    • The core point is the anchor point value
  • Front-end frame Vue / angular / react very suitable for development of single-page application

Basic use

  • view-router
  • It is the core of the plug-vue
  • 1: Download npm i vue-router -S
  • 1.5 (Important): PlugVue.use(VueRouter);
  • 2: vue-router introducing the object main.js import VueRouter form './x.js';
  • 3: Create a route object var router = new VueRouter();
  • 4: Configure routing rules router.addRoutes([路由对象]);
    • Route Object{path:'锚点值',component:要(填坑)显示的组件}
  • 5: will be configured to route object Vue
    • Passed in options -> key referred router
  • 6: stay pit (using the component) <router-view></router-view>

router-link

  • to<router-link to="/xxx/x">点我</router-link>
  • Help us generate href a label
  • Anchor value code maintenance is not convenient, if you need to change the name of the anchor values
    • It is necessary to change the [1 + frequency of use (configuration rules)] code places
Named routes
  • 1: route object to a name { name:'home',path:'/home',component:Home}
  • 2: Description This attribute rule to the router-link
    • <router-link :to="{name:'home'}></router-link>"
    • Find the route object by name, obtain its path, build your own href
  • Greatly reducing maintenance costs, anchor value is changed only in the changing path property can main.js
Parameters of router-link,
  • Vue.prototype.xxx = {add:fn}
  • All components using this.xxx be able to get this object
  • Query String
    • 1: Configuration:to="{name:'detail',query:{id:hero.id} }"
    • 2: Rules {name:'detail',path:'/detail',component:Detail}
    • 3: Get this.$route.query.id
    • 4: Generate <a href="/detail?id=1">
  • path way
    • 4: Generate <a href="/detail/1">
    • 1: Configuration :to="{name:'detail',params:{id:hero.id} }"
    • 2: Rules { name:'detail',path:'/detail/:id'}
    • 3: Get this.$route.params.id
  • Query string parameter configuration
    • router-link once
    • When taken once
  • Configuration Parameters path way
    • router-link once
    • When configured rules of declaration
    • When taken once
  • Code written summary Notes
    • path ways need to be declared in the routing rules location
Aliases

/aThe alias is /b, means that when a user visits /bwhen, URL will remain /b, but the route was matched /a, as if the user access to /athe same.

{ path: '/a', component: A, alias: '/b' }
Redirect
// 方式一:字符串路径path
{ path: '/a', redirect: '/b' }
// 方式二:name
{ path: '/a', redirect: {name: 'b'} }
// 方式三:动态返回重定向目标
{ path: '/a', redirect: to => {
  // 方法接收 目标路由 作为参数;return 重定向的 字符串路径/路径对象 
}}

Phase Summary

  • vue-router using the steps: 1: 2 is introduced: install the plug 3: creating a routing Example 4: configure routing rules 5: The routing object associated vue 6: left pit

  • router-link to = "/ xxx" Named Route

      1. Adding routing rules in the name attribute object
      2. 在router-link中 :to="{ name:"xxx’} "
  • $ Route routing information object, read-only objects

  • $ Router routing operation object, write-only objects

  • Vue-router from the source of FIG.Insert Picture described herein] (https://img-blog.csdnimg.cn/20191225144058496.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3RqeDExMTEx,size_16,color_FFFFFF,t_70)

      1. Vue.use (Object widget); // process will register some global components, or component, and the object to vm hanging properties

      2. And component object to vm hanging manner: Object.defineProperty (Vue.prototype, '$ router', {

        GET: function () {
        return its router objects;

        ​ }

        })

Nested routing

[Image dump the chain fails, the source station may have security chain mechanism, it is recommended to save the picture down uploaded directly (img-W0wz3vwt-1577255773523) (Vue Information / 12-VueJS- Day 3 - dynamic nested routing, access control / 12-VueJS- Day 3 - plug modular / source 4- / 12-VueJS- Day 3 - plug modular .assets / image-20191225142652259.png)]

The need to change the value of the anchor, just to change the image above Profile Posts assembly, to the use of nested route

you

  • Code thoughts
    • 1: router-view subdivision
      • router-view a first layer comprising a router-view
    • 2: Each pit dug to the corresponding individual components
  • Instructions: 1: router-view comprising a router-view 2: Route Route children

Routing guard

It is actually a route change event callback function

  • Global routing guard

    • Frontrouter.beforeEach((to, from,next) => {})
    • Postpositionrouter.afterEach((to, from) => {})
  • Routing exclusive guard

    • const router = new VueRouter({
        routes: [
          {
            path: '/foo',
            component: Foo,
            beforeEnter: (to, from, next) =>{
              // ...
            }
          }
        ]
      })
      
  • Guard in the assembly

    • const Foo = {
        template: `...`,
        beforeRouteEnter (to, from, next) {
          // 在渲染该组件的对应路由被 confirm 前调用
          // 不!能!获取组件实例 `this`
          // 因为当守卫执行前,组件实例还没被创建
          // 但是,可以这样用
            next(vm => {
              // 通过 `vm` 访问组件实例-> 未来的组件this
                vm.msg = '数据在此';
            })
        },
        beforeRouteUpdate (to, from, next) {
      	// 触发条件见下文
          // 可以访问组件实例 `this`
        },
        beforeRouteLeave (to, from, next) {
          // 导航离开该组件的对应路由时调用
          // 可以访问组件实例 `this`
        }
      }
      
    • beforeRouteUpdate trigger conditions (dynamic routing parameters)

      • 1: Routing Configuration

      • {path:"/xxx/:id"}
        
      • 2:router-link

      • <router-link to="/xxx/1"
        
      • <router-link to="/xxx/2"
        
  • next

    • Next Release ();

    • Cancel the navigation (url restored to pre-clicks)next(false)

    • Redirect

      • next('/xxx')
        // 或者
        next({name:'路由对象的name属性'});
        
        
  • to||from

    • .fullPath properties of the object more commonly used, which is the current url

Application guard meta property

  • Routing meta metadata -> meta is whether the rules need to verify routing configuration permissions

    • And the routing object name attribute peer { meta:{ isChecked:true } }
  • Route hook -> run-time access control function

    • After each route matches, render component before router-view

    • router.beforeEach(function(to,from,next) {  
      	// 判断to或from的fullPath即可
      } )
      

Programming Navigation

  • 1: jump to a specific anchor point, and displays the page this.$router.push({ name:'xxx',query:{id:1},params:{name:'abc'} });
  • 2: configuration rules {name:'xxx',path:'/xxx/:name'}
  • 3: According to historical records forward or backward
    • this.$router.go(-1|1);
    • 1 representative further, -1 is take a step back

Transition effects and cache

We need to change the page, ok when the route is changed! At the same time we want to add some effects such as fade, it can be used for transition built-in components

Further, considering the cache problem, coupled with the use of keep-alive binding assembly

So, you see this is the

<transition>
  <keep-alive>
    <router-view></router-view>
  </keep-alive>
</transition>

transition and keep-alive details Reference

Finally, write again

To help make learning easy, efficient and free for everyone to share a large number of resources to help you in becoming a full stack engineers, architects and even the way through the clutter. We are here to recommend a full-stack Learning Exchange front-end circle: ?? 1018453829 welcome to exchange into the group discussion, learning exchanges and common progress.

Some people are passionate about learning, but the lack of direction, and in the vast ocean of knowledge in the seemingly endless, at this time the most important thing is to know which technologies need to focus grasp, avoid doing useful work, the limited energy and to maximize state of.

Finally wish all encounter a problem and do not know how to do the front-end programmers, I wish you all in the future work and interview all the best.

Published 35 original articles · won praise 64 · views 10000 +

Guess you like

Origin blog.csdn.net/tjx11111/article/details/103699009
Recommended