Vue2.0 Notes - vue-router routing

Introduction

Use Vue.js to develop SPA (Single Page Application) single page application.
Vue-router can realize single-page application through html5 history API or hash, that is, no refresh jump, switching address, just switching of components on the page;
vue-router can realize other functions such as passing parameters between pages;

Basic usage

When you want to add vue-router, all we need to do is map components to routes and tell vue-router where to render them.

First we need to define the link url, and vue-router uses <router-link> to wrap the a tag.
HTML:

<div id="app">
    <div>
        <!-- 通过router-link来导航,to属性指定链接, 默认 会渲染成a标签 -->
        <router-link to="/home">Home</router-link>
        <router-link to="/user">User</router-link>
    </div>
    <div>
        <!-- 路由出口,路由匹配到的组件将在这里渲染 -->
        <router-view></router-view>
    </div>
</div>

Javascript:

//1.定义(路由)组件
    var home = {template:'<p>This is Home Page。。。</p>'}
    var user = {template:'<p>This is User Page</p>'}
    //2.定义路由,这是一组路由,每个路由使用一个大括号
    const routes = [
        {path:'/home',component:home},
        {path:'/user',component:user}
    ];
    //3.创建路由实例,然后传入路由配置
    var router= new VueRouter({
       routes   //缩写,相当于routes:routes
    });
    //4.在Vue实例中注入路由
    var vm = new Vue({
        el:'#app',
        router   //缩写,相当于router:router
    });

Just run it and it will run perfectly.

router-link class style

We looked at the console Elements and found that it did become an <a> tag, and also added the classes "router-link-exact-active" and "router-link-active" to the currently selected <router-link>, We can add class styles to it.

You can also reset its name just by configuring it in the router instance.

linkActiveClass:'active'//或其他值

HTML5 History Mode

When we look at the path, the default will be preceded by a # sign, which may look ugly, we can use the HTML5 History mode. This mode makes full use of the history.pushState API to complete URL jumps without reloading the page

const router = new VueRouter({
  mode: 'history',
  routes: [...]
});

And if you do this, the background server needs to be configured, because our application is a single-page client application, and if the background is not properly configured, a 404 page may appear. Then you need a wildcard solution, you can use redirection.
3. Redirect
1. Via path

const routes=[
    ....
    //若为/,表示默认重定向/home路径,*则表示匹配任何则重定向到
    {path:'/',redirect:'/home'}//或者{path:'*',redirect:'/home'}
]

When a match is not found, it will go to this route.
2.
Of course, you can also redirect by route name, provided you set the name parameter for the route

const routes = [
    {path:'/user',component:user,name:'user'},//此时通过name设置路由名称
    {path:'/',redirect:{name:'user'}}//此处通过name属性给与路由名称
];

Nested routes

Nested routing is nothing more than adding routing to routing, just like components.
If user needs login and register

//重新为user定义模板
<template id="user">
    <div>
        <ul>
            <li><router-link to="/user/login">User Login</router-link></li>
            <li><router-link to="/user/regist">User Regist</router-link></li>
        </ul>
        <router-view></router-view>
    </div>
</template>
//为user路由添加子路由
children:[
    {path:'login',component:login},
    {path:'regist',component:regist}
}
//定义组件
var login = {template:'<p>用户登录</p>'}
var regist = {template:'<p>用户注册</p>'}

Run it and it will display normally.
Pay attention to the router-link and router-view in the user template, they are in one-to-one correspondence, which is different from the outside.

router-link tag rendering

As mentioned earlier, the default rendering of router-link is the <a> tag, we can change it through the tag attribute

<router-link to="/user/login" tag="li">User Login</router-link>
<router-link to="/user/regist" tag="li">User Regist</router-link>

Dynamic route matching

If we match a route by path path. For example, we have a User component that is used to render all users with different IDs. Then, we can use "dynamic path parameters" in the routing path of vue-router.
In layman's terms, it's a parameter.

  • String parameter?uname=xiao&pwd=123
  • rest style parameter /yao/456

Of course, if we map the route like this, we must have parameter values. The parameters obtained by the string and the parameters obtained by the rest use different methods.

  • String parameter $route.query
  • rest style parameters $route.params
//字符串参数的方式无需配置映射路径,直接显示
var login = {template:'<p>用户登录,获取参数,{{$route.query}}</p>'}

//rest方式
children:[
    {path:'login',component:login},
    {path:'regist/:uname/:pwd',component:regist}
]
var regist = {template:'<p>用户注册,获取参数,{{$route.params}}</p>'}

Mainly talk about the second dynamic path parameter, it is similar to REST ful, the matching path can be mapped, a "path parameter" uses a colon : mark , when a route is matched, the parameter value will be set to this.$route. params, which can be used inside each component .

Responding to changes in routing parameters

When using route parameters, such as navigating from /user/login to /user/regist, the original component instance is reused . Because both routes render the same component, reuse is more efficient than destroying and recreating. However, this also means that the component's lifecycle hooks will no longer be called

When reusing components, to respond to changes in route parameters, you can simply watch the $route object

watch: {
    '$route' (to, from) {
      // 对路由变化作出响应...
    }
  }

match priority

Sometimes, the same path can match multiple routes. In this case, the priority of matching is in the order of route definition: whoever defines it first has the highest priority.

Programmatic Navigation

router.push adds a route to the current and uses

In addition to using <router-link> to create a tag to define navigation links, we can also use router instance methods to do this by writing code.

router.push(location, onComplete?, onAbort?)

Note: Inside a Vue instance, you can access the router instance via $router. So you can call this.$router.push

This method adds a new record to the history stack , so when the user clicks the browser's back button, they go back to the previous URL.

This method is called internally when you click on the <router-link>, so clicking on <router-link :to="..."> is equivalent to calling router.push(...).

Declarative programmatically
<router-link :to="..."> router.push(...)
//this.$router.push("home");//字符串,值为路由名称
//this.$router.push({path:'/user'});//对象,path指定路径
//this.$router.push({name:'regist',params:{uname:'chen',pwd:123}});//动态参数路由
//this.$router.push({path:'/user/login',query:{uname:'chen',pwd:123}});//带查询参数
以及
router.push({ name: 'user', params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123

Note: If a path is provided, params will be ignored
. You also need to pay attention to whether you use query or params. If your path is in the label mode, use params, otherwise use query

router.replace replaces the current record

Similar to router.push, the only difference is that it doesn't add a new record to the history , but just like its method name - replaces the current history record.

Declarative programmatically
<router-link :to="..." replace> router.replace(...)

Its grammatical structure is exactly the same as the router.push method, but the important thing is that it does not generate a history record.

router.go(n) forward or backward

The parameter of this method is an integer, which means how many steps forward or backward in the history record, similar to window.history.go(n).

// 在浏览器记录中前进一步,等同于 history.forward()
router.go(1)

// 后退一步记录,等同于 history.back()
router.go(-1)

// 前进 3 步记录
router.go(3)

// 如果 history 记录不够用,那就默默地失败呗
router.go(-100)
router.go(100)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324820615&siteId=291194637