Home >Web Front-end >Vue.js >This article will help you quickly understand Vue-Router routing

This article will help you quickly understand Vue-Router routing

WBOY
WBOYforward
2021-12-30 17:55:412220browse

This article brings you knowledge about Vue-Router routing. Vue Router is the official routing manager of Vue.js. It is deeply integrated with the core of Vue.js and can be very conveniently used for the development of SPA applications. I hope everyone has to help.

This article will help you quickly understand Vue-Router routing

1. Quick concept:

1. Backend routing:

1. According to different user URL requests, returns different content, which is essentially the correspondence between the URL request address and the server resource.

2. However, there are performance issues in back-end rendering.

2. Front-end routing:

3. So Ajaxfront-end rendering appears, and front-end rendering can improve performance , but does not support the browser's forward and backward operations.

4. At this time, SPA (Single Page Application) appeared again. The entire website has only one page, and content changes are realized through AjaxPartial Update , while supporting the forward and backward operations of the browser address bar.

5. One of the SPA implementation principles is based on URL address hash (Changes in hash will cause the browser to record changes in access history, but changes in hash will not trigger new URL requests. ). In the process of implementing SPA, the core technical point is front-end routing.

6.Front-end routing displays different page content based on different user events. The essence is the correspondence between user events and event processing functions.

3.Vue Router:

This is the official documentation link. :https://router.vuejs.org/zh/guide/#javascript

Vue Router is the official routing manager of Vue.js. It is deeply integrated with the core of Vue.js and can be very conveniently used for the development of SPA applications.

Its functions are as follows:

1. Support HTML5 history mode or hash mode.

2. Support nested routing.

3. Support routing parameters.

4. Support programmatic routing.

5. Support named routing.

2. Basic usage:

Premise:

The following will demonstrate the basics of Vue Router with an HTML single page Steps for usage. The same principle applies to vue projects. The current basic code of a single page:

nbsp;html>


    <meta>
    <meta>
    <meta>
    <title>Document</title>


    <p>

    </p>
    <script>
        const app = new Vue({
            el:"#app",
            data: {}
        })
    </script>

You can see nothing:

This article will help you quickly understand Vue-Router routing
The following are the specific steps to start using:

1. Import related files:

A single page must first import the vue file and vue-router file so that we can use routing.

<script></script>
<script></script>

2. Add routing link:

The following is a tag provided by vue, which will be rendered as a tag by default. There is a to attribute, which will be rendered as a href attribute, and the default value will be rendered as a hash address starting with #. To put it simply, it means that when the user clicks on different content, he will jump to different content, and this label is what the user wants to click on, which is equivalent to the a label.

<router-link>...</router-link>

Add a page1 and a page2 link to our single page:

<p>
       <router-link>Page1</router-link>
       <router-link>Page2</router-link>
    </p>

3. Add routing padding:

The following one The label is called routing filling bit, which means that components matched by our routing rules in the future will be rendered to the location of router-view. To put it simply, when the user clicks on the routing link, the content will jump. What we know is that the entire page will not jump, but the content will change in the relevant part of the page. This part is the area where the router-view is displayed.

<router-view></router-view>

Add to our page:

        Page1        Page2        <router-view></router-view>     

4. Define the routing component:

Since you want to display different content, you must use one The component saves a copy of its content. Next we define the two components page1 and page2 for a single page.

 <script>
        const Page1 = {
            template: &#39;<h1>我是北极光之夜1号&#39;
        }
        const Page2 = {
            template: &#39;<h1>我是北极光之夜2号&#39;
        }
        const app = new Vue({
            el:"#app",
            data: {}
        })
    </script>

5. Configure routing rules and create routing instances:

routes is an array of routing rules. Each routing rule is a configuration object, which contains at least two attributes: path and component. Path represents the hash address matched by the current routing rule, and component represents the component to be displayed corresponding to the current routing rule. To put it simply, it means which content component corresponds to the address corresponding to the link you click. The path and the address in the router-link tag must be the same, don't make a mistake.

const router = new VueRouter({
            routes: [
                {path:'/page1',component:Page1 },
                {path:'/page2',component:Page2 }
            ]
        })

6. Mount the routing to the Vue root instance:

In order for the routing rules to take effect, the routing object must be mounted to the vue instance object.

 const app = new Vue({
            el:"#app",
            data: {},
            router
        })

7. Effect and single page code:

We are done~

This article will help you quickly understand Vue-Router routing
The complete code above:

nbsp;html>


    
    
    
    Document
    
    <script></script>
    <script></script>


    

       Page1        Page2        <router-view></router-view>     

    <script> const Page1 = { template: &#39;<h1>我是北极光之夜1号&#39; } const Page2 = { template: &#39;<h1>我是北极光之夜2号&#39; } const router = new VueRouter({ routes: [ {path:&#39;/page1&#39;,component:Page1 }, {path:&#39;/page2&#39;,component:Page2 } ] }) const app = new Vue({ el:"#app", data: {}, router }) </script>

3. Route redirection:

Route redirection means that when the user accesses address A, it forces the user to jump to address B, thereby displaying a specific component page.

通过路由规则的redirect属性,指定一个新的路由地址,可以很方便地设置路由的重定向。

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

其中path表示重定向的原地址,redirect表示新地址。

比如第二大点的案例中,刚打开的页面如下,在根目录,但我们想一进入就显示page1,那就给根目录重定向。

This article will help you quickly understand Vue-Router routing
修改路由规则如下:

const router = new VueRouter({
            routes: [             
                {path:'/page1',component:Page1 },
                {path:'/page2',component:Page2 },
                {path:'/',redirect:'/page1'}
            ]
        })

看效果,我没点击就默认进入page1了:

This article will help you quickly understand Vue-Router routing

四.嵌套路由:

功能如下:

  1. 点击父级路由链接显示模板内容。
  2. 模板内容中又有子级路由链接。
  3. 点击子级路由链接显示子级模板内容。

比如我们改进第二大点的案例,当点击page2显示page2内容时,page2里又有两个子路由连接,star和moon,当点击其中一个链接时又能显示对应的star或moon内容。

1.首先给page2组件添加两个子路由链接:

const Page2 = {
            template: `
                 <p>
                 </p><h1>我是北极光之夜2号</h1>
                 <hr>
                 <router-link>Star</router-link>
                 <router-link>Moon</router-link>
                 <hr>
                 `
        }

此时页面也把显示子路由链接出来了:

This article will help you quickly understand Vue-Router routing

2.给两个子路由链接添加路由填充位:

const Page2 = {
const Page2 = {
            template: `
                 

                 

我是北极光之夜2号

                 
                 Star                  Moon                  
                 <router-view></router-view>                  `         }

3.设置两个子组件star与moon的内容:

    const Star = {
            template: '<h2>我是北极光之夜2号下的star</h2>'
        }
        const Moon = {
            template: '<h2>我是北极光之夜2号下的Moon</h2>'
        }

4.配置路由规则:

page2的规则除了path和component属性外,再添加一个children属性,这个属性以数组表示,数组里存放其子路由的规则,其规则也是一样的,套娃套娃。

const router = new VueRouter({
            routes: [
                {path:'/page1',component:Page1 },
                {
                    path:'/page2',
                    component:Page2, 
                    children: [
                        {path: '/page2/star',component:Star},
                        {path: '/page2/moon',component:Moon}
                    ]
                }
            ]
        })

5.效果与单页面代码:

This article will help you quickly understand Vue-Router routing
完整代码:

nbsp;html>


    
    
    
    Document
    
    <script></script>
    <script></script>


    

       Page1        Page2        <router-view></router-view>     

    <script> const Page1 = { template: &#39;<h1>我是北极光之夜1号&#39; } const Page2 = { template: ` <p> <h1>我是北极光之夜2号 <hr/> <router-link to="/page2/star">Star <router-link to="/page2/moon">Moon <hr/> <router-view> ` } const Star = { template: &#39;<h2>我是北极光之夜2号下的star&#39; } const Moon = { template: &#39;<h2>我是北极光之夜2号下的Moon&#39; } const router = new VueRouter({ routes: [ {path:&#39;/page1&#39;,component:Page1 }, { path:&#39;/page2&#39;, component:Page2, children: [ {path: &#39;/page2/star&#39;,component:Star}, {path: &#39;/page2/moon&#39;,component:Moon} ] } ] }) const app = new Vue({ el:"#app", data: {}, router }) </script>

五. 动态路由匹配:

1.动态匹配路由基本使用:

如果某些路由规则的一部分是一样的,只有另一部分是动态变化的,那我们可以把这些动态变化的部分形成路由参数,这些参数就叫做动态路由匹配。简单来说,你先看下面这些路由链接,它们都有/page/,就是后面不一样:

 <router-link>Page1</router-link>
   <router-link>Page2</router-link>
   <router-link>Page3</router-link>

那该咋配置路由呢?这样吗:

const router = new VueRouter({
            routes: [
                {path:'/page/1',component:Page},
                {path:'/page/2',component:Page},
                {path:'/page/3',component:Page}
            ]
        })

这样万一有很多一个个写岂不是太麻烦了,所以引入参数,在动态改变的部分定义为参数,参数前面有一个冒号,那上面可简写成如下,动态部分设为参数 :id 。

const router = new VueRouter({
            routes: [
                {path:'/page/:id',component:Page },
            ]
        })

在组件可以通过以下语法获取当前路由的参数:

$router.params.参数名称

好,再次修改第二大点的案例完成动态路由匹配:

1.定义路由链接:

   <router-link>Page1</router-link>    <router-link>Page2</router-link>    <router-link>Page3</router-link>    <router-view></router-view>    

2.动态配置路由,参数id:

const router = new VueRouter({
    routes: [
        {path:'/page/:id',component:Page1 },
    ]
})

3.设置组件内容,并显示当前路由的参数:

const Page1 = {
    template: '<h1>我是北极光之夜1号,当前id为:{{$route.params.id}}</h1>'
}

看效果:

This article will help you quickly understand Vue-Router routing

2.路由组件传参:

上面的$route与对应路由形成高度耦合,不够灵活啊,所以可以使用props将组件和路由解耦。简单来说,好像也没什么说的,直接看下面实例就能理解了。

2.1 当props为布尔类型:

        const router = new VueRouter({
            routes: [
 // 设置props,如果props为true,router.params会被设置为组件属性
                {path:'/page/:id',component:Page1,props: true },
            ]
        })  
              
        const Page1 = {
// 这时就通过props接收参数,快速简洁的接收参数id和使用它
                    props: ['id'],
                    template: '<h1>我是北极光之夜1号,当前id为:{{id}}</h1>'
                }

能达到一样的效果,且更灵活了,上面记得反过来,先定义组件才配置路由规则,只是为了直观才这样写:

This article will help you quickly understand Vue-Router routing

2.2 当props为对象类型:

            const Page1 = {
        // 这时就通过props接收参数,快速简洁的接收参数对象 并显示
                props: ['name','age'],
                template: `<h1>我是北极光之夜1号,当前id为:{{id}}
                            <hr>
                           姓名为:{{name}} ,年龄为:{{age}} </h1>`
                }
             const router = new VueRouter({
                routes: [
            // props为一个参数对象,它会原样设置为组件属性,
            // 里面的自定义的参数都能传过去,但是id传不了了
                    {path:'/page/:id',component:Page1 , props: {name:'auroras',age: 18} }
                ]
             })

效果,对象props对象里的能获取,id就不行了:
This article will help you quickly understand Vue-Router routing

2.3 当props为函数类型:

这个就什么都能获取。

    const Page1 = {
// 这时就通过props接收参数,快速简洁的接收参数
        props: ['name','age','id'],
        template: `<h1>我是北极光之夜1号,当前id为:{{id}}
                    <hr>
                   姓名为:{{name}} ,年龄为:{{age}} </h1>`
        }
     const router = new VueRouter({
        routes: [
    // props为函数,这个对象接收router对象为自己形参,
    // 里面的自定义的参数和id都能传过去
            {path:'/page/:id',
            component:Page1 , 
            props: router => ({id: router.params.id,name:'auroras',age: 18}) }
        ]
     })

效果:

This article will help you quickly understand Vue-Router routing
当前完整代码:

nbsp;html>


    
    
    
    Document
    
    <script></script>
    <script></script>


    

        Page1         Page2         Page3         <router-view></router-view>         

             <script> const Page1 = { // 这时就通过props接收参数,快速简洁的接收参数对象 props: [&#39;name&#39;,&#39;age&#39;,&#39;id&#39;], template: `<h1>我是北极光之夜1号,当前id为:{{id}} <hr/> 姓名为:{{name}} ,年龄为:{{age}} ` } const router = new VueRouter({ routes: [ // props为函数,这个对象接收router对象为自己形参, // 里面的自定义的参数和id都能传过去 {path:&#39;/page/:id&#39;, component:Page1 , props: router => ({id: router.params.id,name:&#39;auroras&#39;,age: 18}) } ] }) const app = new Vue({ el:"#app", data: {}, router }) </script>

六.Vue-Router命名路由:

为更加方便的表示路由的路径,可以给路由规则起一个别名, 即为“命名路由”。继续改进上面的案例讲解用法:

1.首先给路由规则加一个name属性,这个就是别名:

 const router = new VueRouter({
    routes: [
        {
        name: 'user',
        path:'/page/:id',
        component:Page1 , 
        props: router => ({id: router.params.id,name:'auroras',age: 18}) }
    ]
 })

2.在路由链接中使用:

     

    Page1     Page2     Page3     <router-view></router-view>     

我们把第一个路由链接改进,to前面加上冒号,其中name表示匹配的是哪个路由规则,params表示要传递的参数,看下面是一样的效果:
This article will help you quickly understand Vue-Router routing

七.编程式导航:

  1. 声明式导航:首先声明式导航是指用户通过点击链接完成导航的方式,比如点击a标签或者路由链接这些完成的跳转。

  2. 编程式导航:编程式导航就是说跳转是因为我点击它,它不是链接,但是它在JavaScript里调用了某个API也实现了跳转。

  3. 常用的编程式导航API如下:
this.$router.push('要跳转的hash地址')
this.$router.go(n)

push里直接放要跳转的哈希地址,go方法实现前进和后退,n代表数组,若n为1代表在历史记录中前进一位,-1代表在历史记录中后退一位。

1. this.$router.push(’ '):

重写一个案例,有page1、page2、page3三个路由链接,而在page3里有一个按钮,这个按钮的作用是点击后返回显示page1的内容。这个按钮可不是声明式导航里的链接,就是一个按钮。

1.定义普通的路由链接:

    

    Page1     Page2     Page3     <router-view></router-view>     

2.定义3个组件内容,其中给page3组件里放一个按钮,并绑定点击事件,在事件里通过API导航到page1:

const Page1 = {
    template: `<h1>我是北极光之夜1号</h1>`
}
const Page2 = {
    template: `<h1>我是北极光之夜2号</h1>`
}
const Page3 = {
    template: `<p>
            </p><h1>我是北极光之夜3号</h1>
            <button>返回page1</button>
               `,
    methods: {
        goPage1(){
            this.$router.push('/page/1')
        }
    },
    
}

3.路由规则:

const router = new VueRouter({
                routes: [
                    {path:'/page/1',component: Page1},
                    {path:'/page/2',component: Page2},
                    {path:'/page/3',component: Page3}
                ]
             })

4.看效果:

This article will help you quickly understand Vue-Router routing
5.完整代码:

nbsp;html>


    
    
    
    Document
    
    <script></script>
    <script></script>


    

        Page1         Page2         Page3         <router-view></router-view>     

             <script> const Page1 = { template: `<h1>我是北极光之夜1号` } const Page2 = { template: `<h1>我是北极光之夜2号` } const Page3 = { template: `<p> <h1>我是北极光之夜3号 <button @click="goPage1">返回page1 `, methods: { goPage1(){ this.$router.push(&#39;/page/1&#39;) } }, } const router = new VueRouter({ routes: [ {path:&#39;/page/1&#39;,component: Page1}, {path:&#39;/page/2&#39;,component: Page2}, {path:&#39;/page/3&#39;,component: Page3} ] }) const app = new Vue({ el:"#app", data: {}, router }) </script>

不止href路径,还可以有以下操作:

//字符串形式(路径的名称)
router.push('/page1')
//对象的形式
router.push({path: '/page1'})
//也可以传递参数,命名的路由
router.push({name: '/page1',parmas:{id: 1}})
//带查询参数,变成  /page1?p=id 
//这个挺实用的,比如在某些音乐网页,点击歌单后要导航到另一个该歌单详细界面,此时要带id,详细界面靠此id重新发送请求,请求详细信息
router.push({parh: '/page1',query:{p: 'id' }})

2. this.$router.go(n):

改进第1小点的案例,当我page3跳到page1时,page1里又有一个返回的按钮。我们把n设置为-1,他就会在历史记录中后退一位,后退一位就是page3.
修改page1组件内容:

  const Page1 = {
                template: `<p>
                        </p><h1>我是北极光之夜1号</h1>
                        <button>返回</button>
                           `,
                  methods: {
                    goBack(){
                        this.$router.go(-1)
                    }
            }
        }

效果:

This article will help you quickly understand Vue-Router routing

【相关推荐:《vue.js教程》】

The above is the detailed content of This article will help you quickly understand Vue-Router routing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete