关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

Vue:push()操作

发布时间:2020-03-24 00:00:00

通过VueRouter实例的push()操作,可以进行路由跳转,对于

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

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

举个栗子:

<div id="app"><button @click="test">测试button>   <hr/><router-view>router-view>div><script>                   
    const info   = { template:'Page info'}             //登陆页    const home   = { template:'Page home:{{this.$route.params.uid}}'}            //主页    const detail = { template:'Page detail:{{this.$route.params.id}}'}         //详情页    
    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'})来说是一样的。

 


/template/Home/Zkeys/PC/Static