vuex全家桶系列06-如何使用编程式导航

160 阅读1分钟

1.编程式导航

除了使⽤ <router-link> 创建a标签来定义导航链接,我们还可以借助 router 的实例⽅法,通过编写代码来实现。注意:在 Vue 实例内部,你可以通过 $router访问路由实例。因此你可以调⽤ this.$router.push

声明式:编程式:
< router-link :to="...">router.push(...)
    // 字符串
    this.$router.push('home')
    // 对象
    this.$router.push({
        path: 'home'
    })
    // 命名的路由
    this.$router.push({
        name: 'user',
        params: {
            userId: '123'
        }
    })
    // 带查询参数,变成 /register?plan=private
    this.$router.push({
        path: 'register',
        query: {
            plan: 'private'
        }
    })

2.前进后退:

// 在浏览器记录中前进⼀步,等同于 history.forward()
this.$router.go(1)
// 后退⼀步记录,等同于 history.back()
this.$router.go(-1)
// 前进 3 步记录
this.$router.go(3)
// 如果 history 记录不够⽤,那就默默地失败呗
this.$router.go(-100)
this.$router.go(100)

下面来下看下User.vue的实例:

  • this.$router.push("/"):首页

  • this.$router.push({name: "about" }):关于页

  • this.$router.push({ path: "mylover", query: { name: "linlin", } })

<template>
<div>
    <h1>我是用户路由组件{{$route.params.id}}--{{id}}</h1>
    <h2>{{love}}</h2>
    <button @click="toIndex">跳转到首页</button>
    <button @click="goback">老子要回去</button>
</div>
</template>

<script>
export default {
    created() {
        console.log('我是路由信$route', this.$route);
        console.log("我是当前的路由对象", this.$router);
    },
    //这里就可以接收到路由的id参数了
    // http://localhost:8080/user/2?love=linlin
    props: ["id", "love"],

    methods: {
        toIndex() {
            //第一种🌵
            // this.$router.push("/")
            //第二种🌵
            // this.$router.push({
            //     name: "about"
            // });
            //第三种🌵
            this.$router.push({
                path: "/"
            });
            //扩展
            this.$router.push({
                path: "mylover",
                query: {
                    name: "linlin",
                }
            })
        },
        goback() {
            //go方法的:正数表示前进;负数表示后退
            this.$router.go(3);
        }

    }
};
</script>