Vue Learning Journey Part9: Using vue-router to achieve front-end routing and parameter passing

1. Concept

1. What is routing

To put it simply, routing is the mapping of URL to function. The
visited URL will be mapped to the corresponding function, and the corresponding function will decide what to return to this URL.
Routing is a matching job.

2. Back-end routing and front-end routing

  • 1. Back-end routing:
    For ordinary websites, all hyperlinks are URL addresses. All URL addresses correspond to corresponding resources on the server.
    Each front-end resource corresponds to a URL address. The back-end routing distributes the
    browser in the address bar. every time when switching different url request to the back-end server and the server responds to the request passed to the front display mosaic html file in the background to return different pages
    which means the browser will refresh the page end is not separated before and after

  • 2, the front end of the route:
    For single-page application through the URL for the hash ( #achieved No.) switching between different pages of the page does not refresh
    example: www.xxx.com#/xxxthis format
    at the same time have a characteristic hash: the HTTP request does not contain the relevant hash The content is
    similar to the concept of an anchor point .
    Any characters that appear after the first # will be interpreted by the browser as a location identifier. This means that these characters will not be sent to the server-side
    front-end routing. Just change the content after # will only go to the corresponding position will not reload the web browser requests a page from the server is not re

In a single-page application, this way of switching pages through hash changes is called front-end routing
(forming a difference from back- end routing , and the front-end is responsible for routing)


Second, the basic use

1. Introduction

vue-router is the official routing manager of Vue.js

cdn introduction:

<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

vue-router depends on Vue, so the order of introducing vue-router must be after Vue

When the vue-router package is imported, it will automatically use the Hash routing
URL address and will be automatically added after:#/

2. Create a routing rule object to define the routing matching rules:

When the vue-router package is imported, there is a route constructor named VueRouter in the window global object

new VueRouter()Create a routing rule object and pass a configuration object for the constructor when new

Configuration object which is matched routing rules for each route is an object matching rule

There are two required attributes on the object :
paththe monitored routing connection and componentthe corresponding component to be displayed.
Example:{path:"/login",component:login}

②, and then register the routing rule object in the router attribute of the Vue instance

In this way, after matching the previous routing connection, the corresponding components on the back are displayed on the page to achieve routing

<script>
    // 组件模板对象1
    var login={
        template:"<h1>登录</h1>"
    }
    // 组件模板对象2
    var register={
        template:"<h1>注册</h1>"
    }

    // 创建路由规则对象
    var routerObj=new VueRouter({
        // 定义路由匹配规则
        routes:[
            // component属性的值是模板对象 不是组件引用名称 不加引号
            {path:"/login",component:login},
            {path:"/register",component:register}
        ]
    })

    var vm=new Vue({
       el:'#app',
       data:{},
       methods:{},
       // 将路由规则对象注册到Vue实例上 监听URL地址的变化然后根据规则展示对应的组件
       router:routerObj
    });
</script>

3. Use the <router-view>label placeholder to display the component matched by the routing rule on the label:

vue-router provides an <router-view>element for placeholders
. Components matched by routing rules will be displayed on the label

<div id="app">
    <!-- 跳转的地址前面必须加上井号[#] 因为跳转到的并不是真实页面 而是锚点路由 -->
    <a href="#/login">登录</a>
    <a href="#/register">注册</a>
    
    <!-- 路由规则匹配到的组件会展示到该标签上 -->
    <router-view></router-view>
</div>

Execution process: the
user clicks on the hyperlink on the page and the URL address will be modified.
Because the routing object is registered on the Vue instance, after the URL address is modified, the route will automatically listen to the change of the URL address and then match the routing address
if it matches To the corresponding rule, the corresponding component is displayed on the <router-view>placeholder of the page


Third, <router-link>set the routing link

Vue provides a <router-link>label using the to attribute to specify the connection address
<router-link> label to be routed. The page is rendered as a label by default.

Example:

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

Is equal to:

<a href="#/login">登录</a>
<a href="#/register">注册</a>

You can use the tag attribute to specify the tag to be rendered:

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

Four, redirect routing

Monitor [ /] The root path displays the specified component as soon as it enters the page

var routerObj=new VueRouter({
            // 定义路由匹配规则
            routes:[
                {path:"/",component:login},
                {path:"/login",component:login},
                {path:"/register",component:register}
            ]
        })

Although this method can be implemented, the route anchor displayed when entering the page for the first time is still the root path.
At this time, the real redirect can be achieved by specifying the redirect path :{path:"/",redirect:"/login"}

var routerObj=new VueRouter({
            // 定义路由匹配规则
            routes:[
                {path:"/",redirect:"/login"},
                {path:"/login",component:login},
                {path:"/register",component:register}
            ]
        })

It should be noted that the redirect here is different from the redirect on the server side. The redirect here is that the client modifies the hash value to modify the jump address


Five, highlight effect

When the target route is successfully activated, the link element will automatically set a CSS class name that indicates activation. This class
will be present on the currently loaded component.router-link-active

Then as long as you add styles to this class, you can achieve the highlight effect:

<style>
    .router-link-active
    {
        color: aqua;
        font-size: 40px;
    }
</style>

The class name can also be specified by itself in the route construction options linkActiveClass:

<script>
var routerObj=new VueRouter({
            routes:[
                {path:"/",redirect:"/login"},
                {path:"/login",component:login},
                {path:"/register",component:register}
            ],
            // 自定义激活的类名
            linkActiveClass:"myactiveclass"
        })
</script>
<style>
    .myactiveclass
    {
        color: aqua;
        font-size: 40px;
    }
</style>

Sixth, parameter transmission

Parameter passing is to obtain the parameters carried in the requested URL in the routing component

There are two ways to pass parameters:
query and params

1. query method

Use $routeto get a query attribute in the current routing object. The
query attribute contains all the query parameters carried in it.

<router-link to="/login?id=1">登录</router-link>
<script>
    var login={
        template:"<h1>登录</h1>",
        created()
        {
            console.log(this.$route);
        }
    }
</script>

Insert picture description here
Then use $route.query.属性名can be obtained
can pass multiple parameters:

<router-link to="/login?id=1&name=陈涛">登录</router-link>
<script>
    var login={
    	// 用 $route.query.属性名 来获取参数
        template:"<h1>登录 - {{$route.query.id}} - {{$route.query.name}}</h1>",
        created()
        {
            console.log(this.$route);
        }
    }
</script>

2. Params

$routeThere is one of the current routing objects obtained using params属性
the query parameters carried inside.
Vue-router internally pre-parses the path (request path) into a regular expression and then parses the regular expression into a fullPath.

When requested in this way, it is layered with slashes :

<router-link to="/login/1">登录</router-link>
<script>
  var login={
        template:"<h1>登录</h1>",
        created()
        {
            // 组件的生命周期函数
            console.log(this.$route);
        }
    }
</script>

params property where there are incoming parameters:
Insert picture description here
by $route.params.属性名acquiring
can pass multiple parameters:

<router-link to="/login/1/陈涛">登录</router-link>
<script>
    var login={
        template:"<h1>登录 - {{$route.params.id}} - {{$route.params.name}}</h1>",
        created()
        {
            console.log(this.$route);
        }
    }
</script>

Published 210 original articles · 21 praises · 780,000 views

Guess you like

Origin blog.csdn.net/Piconjo/article/details/105683034