vue 路由、页面传参

3,216 阅读2分钟

1、页面跳转及传值

  • (1)通过router-link进行跳转

  • (2)通过编程导航进行路由跳转

(1)使用 <router-link>映射路由 home.vue 中引入了 header.vue 组件,其中含有导航菜单。 当点击导航菜单的时候,会切换 home.vue 中 <router-link> 中的内容,这种只需要跳转页面,不需要添加验证方法的情况,可以使用 <router-link> 来实现导航的功能:

<template>
  <header class="header">
    <router-link id="logo" to="/home/first">{{logo}}</router-link>
    <ul class="nav">
      <li v-for="nav in navs">
        <router-link :to="nav.method">{{nav.title}}</router-link>
      </li>
    </ul>
</template>

在编译之后,<router-link>会被渲染为<a> 标签, to 会被渲染为 href,当 <router-link>被点击的时候,url 会发生相应的改变,如果使用v-bind 指令,还可以在 to 后面接变量,配合 v-for 指令可以渲染导航菜单。

如果对于所有 id 各不相同的用户,都要使用 home 组件来渲染,可以在 routers.js 中添加动态参数:

{ 
    path: '/home/:id',
    component: Home
}

这样 "/home/user01"、"/home/user02"、"/home/user03" 等路由,都会映射到 Home 组件 然后还可以使用 $route.params.id 来获取到对应的 id。

(2)编程式导航

实际情况下,有很多按钮在执行跳转之前,还会执行一系列方法,这时可以用 this.$router.push(location) 来修改 url,完成跳转。

<div>
  <button class="register">注册</button>
  <button class="sign" @click="goFirst">登录</button>
</div>

methods: {
  goFirst() {
    this.$router.push({path: 'home/first'})
  }
}

push 后面可以是对象,也可以是字符串:

// 字符串
this.$router.push('/home/first')
// 对象
this.$router.push({ path: '/home/first' })
// 命名的路由
this.$router.push({ name: 'home', params: { userId: wise }})

params: 相当于 post 请求,请求参数不会体现在地址栏中。

这种方法会出现如下问题:

如果子页面点击【刷新】按钮时,刚才传过来的参数并不会同步。因为参数没有同步到网页地址栏中。但是如果要让他体现在地址栏中,可以在配置路由时,写在path属性中。 如:

{
  path: 'management/target-pv/pv-list/:userId',
  component: TARGET_PV_LIST,
  name: 'home'
}
浏览器效果如下:
http://localhost:8081/scmis/view/management/target-pv/pv-list/5

这样就解决了刷新的问题。

另外还有一种传参形式:query。

query: 相当于 get 请求,请求参数会体现在地址栏中。

this.$router.push({name: 'home', query: {}});
浏览器效果如下:
http://localhost:8081/scmis/view/management/target-pv/pv-list?id=5

如果传过来的是一个比较长的参数,我们既不想让他在url中显示,又想在刷新的时候参数不丢。可以将传过来的参数存起来如本地缓存(localStorage、session等),这样在每次刷新的时候直接从本地缓存中取出。

2、this.$routerthis.$route有何区别?

上面提到的编程式导航中用this.$router.push()来改变路由,用this.$route.params.userId来得到参数值,那么这两个this.$routerthis.$route看起来非常相近,到底有什么差别呢?

在控制台打印两者可以很明显的看出两者的一些区别,如图:

1.$router为VueRouter实例,想要导航到不同URL,则使用$router.push方法。

2.$route为当前router跳转对象,里面可以获取name、path、query、params等