Learning record-front-end routing Vue-Router

1. Basic concepts and principles of routing

The essence of routing is correspondence

1.1 Backend routing

  • Concept : According to different user URLrequests, return different content
  • Essence : the correspondence between the URLrequest address and server resources

1.2 SPASingle Page Application

  • Back-end rendering (with performance issues)
  • AjaxFront-end rendering (front-end rendering improves performance, but does not support browser forward and backward operations )
  • SPA( Single Page Application) Single page application: The entire website has only one page , and the content change is realized through Ajaxpartial update, and it supports the forward and backward operations of the browser address bar at the same time
  • SPAOne of the realization principles: URLaddress-based hash( hashchanges will cause the browser to record changes in the access history , but hashthe changes will not trigger a new URL request )
  • In the implementation SPAprocess, the core technical point is front-end routing

1.3 Front-end routing

  • Concept : According to different user events , display different page content

  • Essence : the correspondence between user events and event handling functions

1.4 Vue Router

  • Vue RouterIs the Vue.jsofficial route manager
  • It Vue.jsis deeply integrated with the core and can be used for SPAapplication development very conveniently
  • Official website: https://router.vuejs.org/zh/

2. vue-routerThe basic use

2.1 Basic steps

(1) Import related library files

<!-- 导入 vue 文件,为全局 window 对象挂载 Vue 构造函数 -->
<script src="./lib/vue_2.5.22.js"></script>
<!-- 导入 vue-router 文件,为全局 window 对象挂载 VueRouter 构造函数 -->
<script src="./lib/vue-router_3.0.2.js"></script>

(2) Add routing link

<router-link to="/user">User</router-link>
<router-link to="/register">Register</router-link>
  • router-linkIs vuethe label provided in and will be rendered as a alabel by default
  • toProperties will be rendered as hrefproperties by default
  • toThe value of the attribute will be rendered as #the hashaddress at the beginning by default

(3) Add routing padding bits

<router-view></router-view>
  • Route padding (also called route placeholder )
  • Components matched by routing rules in the future will be rendered router-viewwhere they are

(4) Define routing components

var User = {
    
    
    template: '<div>User</div>'
};
var Register = {
    
    
    template: '<div>Register</div>'
};

(5) Configure routing rules and create routing instances

// 创建路由实例对象
var router = new VueRouter({
    
    
    // routes 是路由规则数组
    routes: [
        // 每个路由规则都是一个配置对象,其中至少包含 path 和 component 两个属性:
        // path 表示当前路由规则匹配的 hash 地址
        // component 表示当前路由规则对应要展示的组件
        {
    
    
            path: '/user',
            component: User
        }, {
    
    
            path: '/register',
            component: Register
        }
    ]
});

(6) Mount the route to the Vueroot instance

new Vue({
    
    
    el: '#app',
    // 为了能够让路由规则生效,必须把路由对象挂载到 vue 实例对象上
    router // ES6写法
});

2.2 Route redirection

  • When the user visits the address A, the user is forced to jump to the address C to display the specific component page
  • By redirectspecifying a new routing address through the attributes of the routing rule , you can easily set the redirection of the routing
var router = new VueRouter({
    
    
    routes: [
        // 其中,path 表示需要被重定向的原地址,redirect 表示将要被重定向到的新地址
        {
    
    
            path: '/',
            redirect: '/user'
        }, {
    
    
            path: '/user',
            component: User
        }, {
    
    
            path: '/register',
            component: Register
        }
    ]
});

3. vue-routerNested routing

3.1 Nested routing function

3.2 concrete realization

<!-- 被 vm 实例所控制的区域 -->
<div id="app">
    <router-link to="/user">User</router-link>
    <router-link to="/register">Register</router-link>

    <!-- 路由占位符 -->
    <router-view></router-view>
</div>

<script>
    const User = {
     
     
        template: '<h1>User 组件</h1>'
    };

    const Register = {
     
     
        template: `<div>
      <h1>Register 组件</h1>
      <hr/>

      <!-- 子路由链接 -->
      <router-link to="/register/tab1">tab1</router-link>
      <router-link to="/register/tab2">tab2</router-link>

      <!-- 子路由的占位符 -->
      <router-view></router-view>
    <div>`
    };

    const Tab1 = {
     
     
        template: '<h3>tab1 子组件</h3>'
    };

    const Tab2 = {
     
     
        template: '<h3>tab2 子组件</h3>'
    };

    // 创建路由实例对象
    const router = new VueRouter({
     
     
        // 所有的路由规则
        routes: [{
     
     
                path: '/',
                redirect: '/user'
            }, {
     
     
                path: '/register',
                redirect: '/register/tab2'
            }, {
     
     
                path: '/user',
                component: User
            },
            // children 数组表示子路由规则
            {
     
     
                path: '/register',
                component: Register,
                children: [{
     
     
                    path: '/register/tab1',
                    component: Tab1
                }, {
     
     
                    path: '/register/tab2',
                    component: Tab2
                }]
            }
        ]
    });

    // 创建 vm 实例对象
    const vm = new Vue({
     
     
        // 指定控制的区域
        el: '#app',
        data: {
     
     },
        // 挂载路由实例对象
        // router: router
        router
    })
</script>

4. vue-routerDynamic routing matching

4.1 Basic usage

var router = new VueRouter({
    
    
    routes: [
        // 动态路径参数 以冒号开头
        {
    
    
            path: '/user/:id',
            component: User
        }
    ]
});
const User = {
    
    
    // 路由组件中通过$route.params获取路由参数
    template: '<div>User {
    
    { $route.params.id }}</div>'
};

4.2 Passing parameters

$routeIt is highly coupled with the corresponding route and is not flexible enough, so it can be used propsto decouple components and routes

(1) The value of props is of Boolean type

const router = new VueRouter({
    
    
    routes: [
        // 如果 props 被设置为 true,route.params 将会被设置为组件属性
        {
    
    
            path: '/user/:id',
            component: User,
            props: true
        }
    ]
});
const User = {
    
    
    props: ['id'], // 使用 props 接收路由参数
    template: '<div>用户ID:{
    
    { id }}</div>' // 使用路由参数
};

(2) The value of props is the object type

const router = new VueRouter({
    
    
    routes: [
        // 如果 props 是一个对象,它会被按原样设置为组件属性
        {
    
    
            path: '/user/:id',
            component: User,
            props: {
    
    
                uname: 'lisi',
                age: 12
            }
        }
    ]
});
const User = {
    
    
    props: ['uname', 'age'],
    template: `<div>用户信息:{
     
     {uname + '---' + age}} </div>`
};

(3) The value of props is a function type

const router = new VueRouter({
    
    
    routes: [
        // 如果 props 是一个函数,则这个函数接收 route 对象为自己的形参
        {
    
    
            path: '/user/:id',
            component: User,
            props: route => ({
    
    
                uname: 'zs',
                age: 20,
                id: route.params.id
            })
        }
    ]
});
const User = {
    
    
        props: ['uname', 'age', 'id'],
        template: `<div>用户信息: {
    
    {
    
    uname + '---' + age + '---' + id}}</div>'
};

5. vue-routerNaming the route

In order to express the route of the route more conveniently , you can give the route rule an alias, that is, " named route "

<router-link :to="{ name: 'myName', params: { id: 123 }}">User</router-link>
const router = new VueRouter({
    
    
    routes: [{
    
    
        path: '/user/:id',
        name: 'myName',
        component: User
    }]
});

6. vue-routerProgrammatic navigation

6.1 Two ways of page navigation

  • Declarative navigation : The way to achieve navigation by clicking on a link is called declarative navigation, for example: linksvue in ordinary web pages or<router-link></router-link>
  • Programmatic navigation : the way to achieve navigation by invoking the JavaScriptform is APIcalled programmatic navigation. For example:location.href

6.2 Basic usage of programmatic navigation

Commonly used programmatic navigation is APIas follows:

  • this.$router.push('hash地址')
  • this.$router.go(-1) (Take a step back)
const User = {
    
    
    template: '<div><button @click="goRegister">跳转到注册页面</button></div>',
    methods: {
    
    
        goRegister: function() {
    
    
            // 用编程的方式控制路由跳转
            this.$router.push('/register');
        }
    }
};

6.3 Programmatic navigation parameter rules

router.push()

// 字符串(路径名称)
router.push('/home');

// 对象
router.push({
    
    
    path: '/home'
});

// 命名的路由(传递参数)
router.push({
    
    
    name: '/user',
    params: {
    
    
        userId: 123
    }
});

// 带查询参数,变成 /register?uname=lisi
router.push({
    
    
    path: '/register',
    query: {
    
    
        uname: 'lisi'
    }
});

Guess you like

Origin blog.csdn.net/Jack_lzx/article/details/110960226