$router $route区别 路由跳转的三种方式 及两种传参方式params query

124 阅读1分钟

router和route 区别

简单理解为,route是用来获取路由信息的,router是用来操作路由的

route是路由信息对象,每一个路由都会有一个route对象,是一个局部的对象,里面主要包含路由的一些基本信息,比如name、meta、path、hash、query、params、fullPath、matched、redirectedFrom...

router是VueRouter的实例,通过Vue.use(VueRouter)和VueRouter构造函数得到一个router的实例对象,这个对象中是一个全局的对象,他包含了所有的路由包含了许多关键的对象和属性

router对象是全局路由的实例,是router构造方法的实例

路由跳转的三种方式

  1. $router.go()

    $router.back 后退

    页面路由跳转 router.go(-1)为后退,router.go(-1)为前进 $router.forward()为前进

  2. $router.push()

    • 字符串this.$router.push('home')
    • 对象this.$router.push({path:'home'})
    • 命名的路由this.$router.push({name:'user',params:{userId:123}})
    • push方法其实和是等同的。

    *注意:push方法的跳转会向 history 栈添加一个新的记录,当我们点击浏览器的返回按钮时可以看到之前的页面。

  3. $router.replace() 常用来做404页面

    push方法会向 history 栈添加一个新的记录,而replace方法是替换当前的页面,

    不会向 history 栈添加一个新的记录

    this.$router.replace('/') 跳转到首页

路由跳转参数两种传递方式

1.params传递

写法

使用params传参只能使用name进行引入

this.$router.push(name: '路由name名称',params: { id: 1, name:cc}) 
params只能使用name 传递 
    获取参数this.$route.params.id 
    
    未在路由path中配置 例:{name:'aa',path:'/aa', component: () => import('../views/aa/index.vue')} 
    路由地址栏中不会显示任何东西 例:http//:localhost:8080/aa 
    
    在路由path中配置 例:{name:'aa',path:'/aa/:id/:name', component: () => import('../views/aa/index.vue')} 
    路由地址栏中 例:http//:localhost:8080/aa/1/cc 
    路由配置path页面刷新会保留参数,不配刷新丢失,并为必传(跳转未携带报错)

2.query传递

    this.$router.push(name: 'aa',query: {id: 1, name: aa })
    this.$router.push(path: '/aa',query: {id: 1, name: aa }) 
    地址栏均展示 http//:localhost:8080/aa?id=1&name=aa

另外

    路由配置 {name:'aa',path:'/aa/:id', component: () => import('../views/aa/index.vue')} 
    this.$router.push({ path: '/aa/1' }) || this.$router.push('/aa/1') 
    此种在或者时为this.$route.params 
    
    路由中不配置{name:'aa',path:'/aa', component: () => import('../views/aa/index.vue')} 
    this.$router.push( ’/aa?id=1' }) 
    此种在或者时为this.$route.query.id