Vue-Router 源码分析(七) VueRouter.push()的详解

通过VueRouter实例的push()操作,可以进行路由跳转,对于<router-link/>组件来说,它绑定的是click事件,最后也是通过执行push()方法来进行路由跳转的。

对于push()方法来说,一共可以传入三种形式的参数:

  • 字符串形式,值为路劲
  • 含有name的对象形式,可以搭配params属性传递参数
  • 含有path的对象形式

举个栗子:

<div id="app">
    <button @click="test">测试</button>   
    <hr/>
    <router-view></router-view>
</div>
<script>                   
    const info   = { template:'<div>Page info</div>'}             //登陆页
    const home   = { template:'<div>Page home:{{this.$route.params.uid}}</div>'}            //主页
    const detail = { template:'<div>Page detail:{{this.$route.params.id}}</div>'}         //详情页
    
    const router = new VueRouter({
        routes:[                                   
            {path:'/info',component:info},
            {path:'/home/:uid',component:home,name:'home'},
            {path:'/detail/:id',component:detail,}
        ]
    })
    const app = new Vue({                                                     
        el:'#app',
        data:{no:0},
        router:router,
        methods:{
            test(){
                this.no = this.no%3+1;
                switch(this.no){                         //点击测试按钮将依次跳转到三个不同的组件,跳转时使用的push参数也不同
                    case 1:
                        this.$router.push('/info')
                        break;
                    case 2:
                        this.$router.push({name:'home',params:{uid:10}})
                        break;
                    case 3:
                        this.$router.push({path:'/detail/15'})
                        break;
                }
            }
        }
    })
</script>

点击按钮时分别执行三个不同参数的push操作,如下:

我们执行push()进行路由跳转时,会执行VueRouter源码内History对象上的push()操作,然后会执行transitionTo()函数进行路由跳转,在该函数内首先会执行normalizeLocation对参数做出修正,统一修正为一个对象,因此对于push('/login')和push({path:'/login'})来说是一样的。

猜你喜欢

转载自www.cnblogs.com/greatdesert/p/12475265.html