第七篇:Vue的路由逻辑跳转

路由逻辑跳转

我们之前学习的跳转页面使用的是router-link进行跳转,router-link的方式类似a标签进行跳转,且与a标签来相比并不会导致页面刷新,但我们有时候需要在某些逻辑或普通按钮上完成页面跳转。(router-link最终在页面上解析为的样式是a标签)

  • 很多时候,我们需要通过普通按钮的逻辑,或是直接在某些逻辑中完成页面的跳转
  • 可以通过在逻辑中用 this.$router.push() 来完成前往目标页,两种语法如下
    • this.$router.push('路径')
    • this.$router.push({name: '路由名'})
  • 在做移动端项目时,没有像浏览器那样的前进后台键,页可以用 this.$router.go() 来完成前进后退,语法如下
    • 前进后退:this.$router.go(正负整数),正数代表前进,负数代表后退,数值就是步长

示例代码:

<template>
    <div class="home">
        <Nav/>
        <h1>主页</h1>
        <button @click="goPage('/first')">前往第一页</button>
        |
        <button @click="goPage('/second')">前往第二页</button>
        |
        <button @click="goBack(-1)">后退一页</button>
        |
        <button @click="goBack(-2)">后退二页</button>
        |
        <button @click="goBack(1)">前进一页</button>
    </div>
</template>
 
<script>
    import Nav from '@/components/Nav'
 
    export default {
        methods: {
            goPage(path) {
                // 可以通过 this.$router 完成逻辑跳转
                this.$router.push();
            },
            goBack(num) {
                // 一般在移动端项目上运用
                this.$router.go(num); 
            }
        },
        components: {
            Nav,
        }
    }
</script>
原文地址:https://www.cnblogs.com/cnhyk/p/12324754.html