导航方式

在页面中,导航实现有2种方式:

声明式导航

它就是先在页面中定义好跳转的路由规则,vueRouter中通过 router-link组件来完成

<!-- 声明式导航 -->
<router-link to="/hello" tag="p">去hello</router-link>
<!--  声明式导航传参 -->
<router-link :to="{ path: '/news/199' }" tag="p">去news</router-link>
<!--  声明式导航name方式 -->
<router-link :to="{ name: 'user_list' }" tag="p">去用户列表</router-link>

编程式导航

简单来说,编程式导航就是通过JavaScript来实现路由跳转

<template>
    <div id="app">
        <router-view></router-view>
        <!-- 编程式导航 -->
        <button @click="goToNews()">点击去新闻页面</button>
    </div>
</template>
<script>
export default {
    // 后续写的所有以前的实例的属性以后都需要写在`export default`
    name: "App",
    components: {},
    methods: {
        goToNews: function() {
            // 编程式导航传参
            // this.$router.push({path: "/news",query: { news_id: 1216, author: "zhangsan" },});
            // this.$router.push({ path: "/news/133" });
            // 编程式导航传参name
            this.$router.push({name: "user_list",params: {id: 123456}})
            // this.$router.go( n );  //n为数字  负数为回退
        },
    },
};
</script>

注意:

编程式导航在跳转到与当前地址一致的URL时会报错,但这个报错不影响功能:

如果患有强迫症,可以在路由入口文件index.js中添加如下代码解决该问题:

// 获取VueRouter原型上的push
const originalPush = VueRouter.prototype.push;
// 对原先的push方法进行重写
VueRouter.prototype.push = function push(location) {
    // 在原先的代码基础上加了一个异常捕获,且并没有输出异常,所以就看不到报错了。
    return originalPush.call(this, location).catch((err) => err);
};

参数获取

<template>
    <div>
        <!-- 可以在视图中直接接收路由参数,但是一般不这么用 -->
        这是news组件{{$route.params.id}}
    </div>
</template>
<script>
export default {
    // 原先new Vue的时候可以写的属性,都可以在这里写
    created() {
        console.log(this.$route.params.id);
        
    },
}
</script>

面试题问题:

this.$routerthis.$route有什么区别?

答:$router是用于做编程式导航的(改变路由的);$route是用户获取路由参数的。


一沙一世界,一花一天堂。君掌盛无边,刹那成永恒。