vue-router传递参数的方式以及$route和$router的区别

vue-router 传参的方式。

这里讲<router-link>的代码方式。

params的类型

传参数

  1. 创建一个组件user,并在router/index.js注册。
  2. 注册时需要在path后多加一个"/:参数",比如 /user/:userId,用于传参
  3. 在user父路由(这里是Vue组件)的template内使用它
  4. 在<router-link>的to参数内通过动态绑定传递参数userId,参数变量来自父路由。
  5. 如果不通过<router-link>跳转,也可以在methods中写一个方法,使用 $router.push() 或 $router.replace() 来进行跳转,括号中内容的填写方法与<router-link>的to参数内容填写方法基本一样。
<template>
  <div id="app">
    <router-link :to="'/user/'+userId" tag="button" replace>用户</router-link>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      userId: "lisi"
    };
  }
};
</script>

取参数

  1. 在user组件内用this.$route.params.userId获取参数(如果在template内获取,需去掉this)
<template>
  <div>
    <h2>我是用户</h2>
    <p>我是{{userId}}的内容</p>
  </div>
</template>

<script>
export default {
  name: "User",
  data() {
    return {
      userId: this.$route.params.userId
    };
  }
};
</script>

query的类型

传参数

  1. 创建一个组件profile,并在router/index.js注册
  2. 在profile父路由(这里是Home组件)的template内使用它
  3. 然后在to参数内通过动态绑定一个对象传递参数,该对象包含to的路径以及需要传递的参数query
  4. 如果不通过<router-link>跳转,也可以在methods中写一个方法,使用 $router.push() 或 $router.replace() 来进行跳转,括号中内容的填写方法与<router-link>的to参数内容填写方法基本一样。
<template>
  <div>
    <h2>我是首页</h2>
    <router-link
      :to="{path:'/home/profile',query:{age:18,name:'lily',height:1.88}}"
      tag="button"
      replace
    >个人信息</router-link>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: "Home"
};
</script>

取参数

  1. 在profile组件内用this.$route.query.xxx 获取参数(如果在template内获取,需去掉this)
<template>
  <div>
    <h2>我是个人页面</h2>
    <p>我是个人页面的内容</p>
    <p>{{$route.query.age}}</p>
    <p>{{$route.query.name}}</p>
    <p>{{$route.query.height}}</p>
  </div>
</template>

<script>
export default {
  name: "Profile"
};
</script>

$route和$router的区别

$route 指向的是当前活跃的路由,即当前被选中的路由。

$router 指向的是 /router/index.js 中的 Router对象 

注意,所有组件都继承自Vue类的原型,即组件的原型指向Vue的原型。

猜你喜欢

转载自blog.csdn.net/weixin_42207975/article/details/106976813