Vue

vue路由传参

2018-08-14  本文已影响290人  lesdom

路由基础知识

router和route的区别

route,是一个路由。

{ path: '/a', component: A }

routes,是一组路由。

const routes = [
    { path: '/a', component: A },
    { path: '/b', component: B }
]

router,是一个管理者,它管理了一组route。

const router = new VueRouter({
    routes // routes: routes 的简写
})

我举一个形象化的例子:route就好比一座房子,routes就好比一排房子,router就是一个手里有钥匙的人。你想进入哪个房子,就拿着对应的钥匙进去。你想往哪个屋子里放什么东西,你就带着东西进去。

这样一来,我觉得你应该可以区分开routerroute了。
当你想要使用编程时导航传参跳转页面的时候,是用router。也就是说人拿着对应的钥匙开门的动作。
当你想获取并使用接收到的参数的时候,是用route。也就是说这些参数都是房子里的物品。

为什么可以在组件中使用$router$route

main.js

import Vue from 'vue'
import App from './App'
import router from './router'
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

main.js文件中,你将router对象引入,并且将它用作了vue实例的属性,所以你可以在组件中使用this.$routerthis.$route

编程式导航

params传参和query传参的区别

1、params相当于post请求,参数不会在地址栏显示;
  query相当于get请求,参数会显示在地址栏。
2、/data/:id匹配/data/1/data/2,params为路径;
  /data?id=1/data?id=2,query为参数。
3、刷新页面时,params参数有可能会消失,query不会消失。
  当使用下述方式一传参时,params参数会消失;
  当使用下述方式二传参时,params参数不会消失;
总结:
1、一般不重要的参数都使用query传参
2、必要的数据通过传参来实现,能从接口获取的数据就直接调接口

通过params接收参数

方式一

路由配置
{
  path: '/one',
  name: 'One',
  component: One
}
传参组件
<button @click=one> one </button>
one() {
  this.$router.push({
    name: "One",
    params: { id: 1 }
  });
},
接收参数组件
this.$route.params.id

方式二

路由配置
{
  path: '/two/:id',
  name: 'Two',
  component: Two
}
传参组件
<button @click=two(2)> two </button>
two(id) {
  this.$router.push({
    path: `/two/${id}`
  });
}
接收参数组件
this.$route.params.id

通过query接收参数

方式一

路由配置
{
  path: '/three',
  name: 'Three',
  component: Three
}
传参组件
<button @click=three> three </button>
three() {
  this.$router.push({
    path: '/three',
    query: { id: 3 }
  });
},
接收参数组件
this.$route.query.id

方式二

路由配置
{
  path: '/four',
  name: 'Four',
  component: Four
}
传参组件
<button @click=four> four </button>
four() {
  this.$router.push({
    name: "Four",
    query: { id: 4 }
  });
}
接收参数组件
this.$route.query.id

动态路由

动态路由也就是通过params接收参数的第二种方式,在这里我主要介绍一下使用这种方式如何传多个参数。

路由配置
{
  path: '/two/:id/:name',
  name: 'Two',
  component: Two
}
传参组件
<button @click=two()> two </button>
two() {
  this.$router.push({
    path: "/two/2/lee"
  });
}
接收参数组件
this.$route.params.id
this.$route.params.name
上一篇下一篇

猜你喜欢

热点阅读